大象传媒

JavaScript mouse events example

This script has been written to create two functions, mouseOver() and mouseOut().

Line 1: <script>
Line 2: function mouseOver() {
Line 3: document.getElementById("demo").style.color = "red";
Line 4: }
Line 5: function mouseOut() {
Line 6: document.getElementById("demo").style.color = "black";
Line 7: }
Line 8: </script>

The <script> and </script> tags on lines 1 and 8 are used to let the browser know that anything contained between these tags is written in JavaScript.

Within the <script> and </script> tags it is possible to write JavaScript code or link to an external JavaScript file.

Lines 2-4 show the function called mouseOver(). This function will change the style of an element to red if the ID of that element is called 'demo'.

Lines 5-7 show the function called mouseOut(). This function will change the style of an element to black if the ID of that element is called 'demo'. For this code to run, it is necessary for there to be an HTML element with the ID 'demo'.

In the HTML shown below a heading is being used. This heading is identified as 'demo'.

<h1 id="demo" onmouseover="mouseOver()" onmouseout="mouseOut()">Welcome</h1>
1. Welcome in black with cursor near. 2. Welcome in red with cursor hovering over. 3. Welcome in black with cursor near.
  1. This heading will display the word 鈥榃elcome鈥 on screen.
  2. The mouseOver() function is activated if an onmouseover event occurs. This means it will run if the mouse cursor is placed over the word welcome. The mouseOver() function is set to change the style to red.
  3. If the user moves the mouse away from the word 鈥榃elcome鈥 then the text colour would change to black again because the mouseOut() function would be triggered by the onmouseout event. The onmouseout event activates the function for mouseOut() when the cursor is moved away from the word welcome.