JavaScript
Some common tasks that can be performed using JavaScript relate to how the webpage responds to action taken by the user using their mouse or touchscreen.
JavaScript mouse events
Using JavaScript, functions are created that will change what appears on screen depending upon what the user does with the mouse.
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>
- This heading will display the word 'Welcome' on screen.
- 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'. ThemouseOver()
function is set to change the style to red. - If the user moves the mouse away from the word 'Welcome' 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 formouseOut()
when the cursor is moved away from the word 'Welcome'.
Reminder:
onmouseout
- occurs when the cursor is moved away from an element such as a button or a heading.onmouseover
- occurs when the cursor is hovered over an element such as a button or a heading.