Change color on multiple text elements on mouseover using JavaScript

Change color on multiple text elements on mouseover using JavaScript

Posted by Ervin Adams on July 28, 2022

Change color on multiple text elements on mouseover using JavaScript

Change color on multiple text elements on mouseover using JavaScript

Posted by Ervin Adams on July 28, 2022

Steps to change color on multiple text elements on mouseover in JavaScript:

Step 1. Add id to div wrapper element or whatever element your using

<div id="main-wrapper"></div>

Step 2. Add class to p elements. These element will change color on mouseover

<p class="change-color">Change color on mouse over</p>
<p class="change-color">Change color on mouse over again</p>

Step 3. Place p elements in div wrapper

<div id="main-wrapper">
   <p class="change-color">Change color on mouse over</p>
   <p class="change-color">Change color on mouse over again</p>
</div>

Step 4. Identify div wrapper element in JavaScript using id

const mainWrapper = document.getElementById('main-wrapper');

Step 5. Identify p elements in JavaScript using class

const changeColor = document.getElementsByClassName('change-color');

Step 6. Add mouseover event to div wrapper element by using the id in JavaScript

mainWrapper.addEventListener('mouseover', function handleMouseOver() {});

Step 7. Place p elements in mouseover event and loop through p elements using class

mainWrapper.addEventListener('mouseover', function handleMouseOver() {
    for (let i = 0; i < changeColor.length; i++) {
      changeColor[i].style.color = '#05a30d';
    }
});

Step 8. Do the same as above for mouseout

mainWrapper.addEventListener('mouseout', function mouseOut() {
    for (let i = 0; i < changeColor.length; i++) {
      changeColor[i].style.color = '#000000';
    }
});