Home Change Text color on Mouseover using JavaScript
Post
Cancel

Change Text color on Mouseover using JavaScript

Change Text color on Mouseover using JavaScript

To change an element’s text color on mouseover:

  1. Add a mouseover event to the element, changing its text color when the user hovers over it.
  2. Add a mouseout event to the element, changing its text color back to the default when the user moves their cursor out.

Here is the HTML for the examples in this article.

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="box">Apple, Pear, Banana</div>

    <script src="index.js"></script>
  </body>
</html>

And here is the related JavaScript code.

1
2
3
4
5
6
7
8
9
10
11
const box = document.getElementById('box');

// 👇️ Change text color on mouseover
box.addEventListener('mouseover', function handleMouseOver() {
  box.style.color = 'red';
});

// 👇️ Change text color back on mouseout
box.addEventListener('mouseout', function handleMouseOut() {
  box.style.color = 'black';
});

GIF

We selected the element using the document.getElementById() method.

We then added a mouseover event listener to the element.

The mouseover event is fired every time a user’s cursor is moved onto the element or one of its child elements.

If the user hovers over the element, the handleMouseOver function is invoked, where we use the style object to change the element’s text color to red.

We also added a mouseout event listener to the same element.

You could use this approach to change any element’s text color on hover, it doesn’t have to be the element on which the event was dispatched.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="box" style="margin-bottom: 100px; margin-top: 100px">
      Hover over me
    </div>

    <div id="text">Example text content</div>

    <script src="index.js"></script>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
const box = document.getElementById('box');

const textDiv = document.getElementById('text');

// 👇️ Change text color on mouseover
box.addEventListener('mouseover', function handleMouseOver() {
  textDiv.style.color = 'red';
});

// 👇️ Change text color back on mouseout
box.addEventListener('mouseout', function handleMouseOut() {
  textDiv.style.color = 'black';
});

GIF

If the user hovers over the first div element, the text color of the second div gets changed to red.

If they move their cursor out, the color is changed back to black.

This post is licensed under CC BY 4.0 by the author.

PixelPlusUI ROM [Android12] Realme 6, 6i, 6s and Realme 7, Narzo 20 Pro, Narzo 30 4G (G90T Series) (RM6785) [OFFICIAL]

crDroidAndroid v9.0 ROM [Android13] Realme 6, 6i, 6s and Realme 7, Narzo 20 Pro, Narzo 30 4G (G90T Series) (RM6785) [OFFICIAL]

Comments powered by Disqus.