Javascript: Mouse event

This entry is part 26 of 27 in the series Javascript Tutorial

Mouse event is probably the most common event used in Javascript or web programming.

<!DOCTYPE html>
<html>
<head>
    <script>
        function mouseOver() {
            document.getElementsByClassName("lineClass")[0].style.color = "#C0D9FE";
            document.getElementsByClassName("lineClass")[1].style.color = "#C0D9FE";
            document.getElementsByClassName("lineClass")[2].style.color = "#C0D9FE";
        }
        function mouseOut() {
            document.getElementsByClassName("lineClass")[0].style.color = "silver";
            document.getElementsByClassName("lineClass")[1].style.color = "silver";
            document.getElementsByClassName("lineClass")[2].style.color = "silver";
        }
    </script>
</head>
<body>
<div class="lineClass">This is line 1</div>
<div class="lineClass">This is line 2</div>
<div class="lineClass">This is line 3</div>
<h1 onmouseover="mouseOver();" onmouseout="mouseOut();">Mouse over this text</h1>

</body>
</html>

JS Fiddle

We have bind 2 events to a single h1 element.  When the mouse is over the line, mouseOver function is called changing the lineClass related lines to a different color.

Look at how lineClass has turned the 3 div lines into an array with 3 items in the array.  They are accessed with [0], [1] and [2].

You can also pass the lineClass into a variable.  This will make the code look cleaner.

<!DOCTYPE html>
<html>
<head>
    <script>
        function mouseOver() {
            var lineC = document.getElementsByClassName("lineClass")
            lineC[0].style.color = "#C0D9FE";
            lineC[1].style.color = "#C0D9FE";
            lineC[2].style.color = "#C0D9FE";
        }
        function mouseOut() {
            var lineC = document.getElementsByClassName("lineClass")
            lineC[0].style.color = "red";
            lineC[1].style.color = "red";
            lineC[2].style.color = "red";
        }
    </script>
</head>
<body>
<div class="lineClass">This is line 1</div>
<div class="lineClass">This is line 2</div>
<div class="lineClass">This is line 3</div>
<h1 onmouseover="mouseOver();" onmouseout="mouseOut();">Mouse over this text</h1>

</body>
</html>

JS Fiddle – simplified

In the above simplified JS Fiddle, I have passed the lineClass into a variable lineC as shown in line 2 below.

function mouseOver() {
    var lineC = document.getElementsByClassName("lineClass")
    lineC[0].style.color = "#C0D9FE";
    lineC[1].style.color = "#C0D9FE";
    lineC[2].style.color = "#C0D9FE";
}
Series Navigation<< Javascript: Events