WDD  Β·  Web Design & Development

JavaScript: Events and Mouse Handling

Lesson 10 of 13 Approx 3 hrs (split over two periods)

Learning intentions

  • Understand what JavaScript is and why it is used to make web pages interactive
  • Know how to write inline event handlers using onmouseover and onmouseout
  • Know how to use document.getElementById() to target an element and change its style or innerHTML
  • Be able to use mouse event handlers to call simple JavaScript functions

Success criteria

  • I can explain what JavaScript does and how it differs from HTML and CSS
  • I can write onmouseover and onmouseout event handlers on HTML elements
  • I can write a JavaScript function that changes an element's style property using document.getElementById()
  • I can write a JavaScript function that changes an element's text using innerHTML
  • I can identify and fix common JavaScript errors (case sensitivity, camelCase, missing brackets)
Warm up β€” what do you already know?

Answer before the lesson begins.

1. What is JavaScript mainly used for in web development?

2. What is the purpose of an HTML id attribute?

3. Which CSS rule changes a link's text colour to red while the pointer is over it?

Key vocabulary

JavaScript
A scripting language that runs in the browser and makes web pages interactive. It can respond to user actions and change what is displayed on the page without reloading.
event
An action that happens in the browser β€” such as a mouse click, a mouse movement, or a key press. JavaScript can detect events and run code in response.
event handler
An attribute added to an HTML element that specifies JavaScript code to run when a particular event occurs. For example: onmouseover="doSomething()".
onmouseover
An event handler that fires when the mouse pointer moves onto the element. Used to trigger visual changes as the user hovers over an element.
onmouseout
An event handler that fires when the mouse pointer moves off (leaves) the element. Typically used to reverse changes made by onmouseover.
document.getElementById()
A JavaScript method that finds and returns an HTML element by its id attribute. Used to target specific elements so their properties can be changed.
innerHTML
A JavaScript property that gets or sets the HTML content (text) inside an element. Setting element.innerHTML = "Hello" replaces the element's content with "Hello".
style property
A JavaScript property that gives access to an element's CSS styles. Properties use camelCase: backgroundColor instead of background-color.

JavaScript: Events and Mouse Handling

What is JavaScript?

HTML defines the structure and content of a web page. CSS controls the appearance and layout. JavaScript is the third layer β€” it makes pages interactive. JavaScript runs directly in the browser and can respond to what the user does: moving the mouse, clicking buttons, typing text, and more.

In the N5 course, we use JavaScript to detect mouse events and update what the user sees β€” changing colours, text, and images without reloading the page.

How JavaScript is added to a page

JavaScript is written inside <script> tags, placed before the closing </body> tag. Event handlers are added directly as attributes on HTML elements:

<!-- The event handler calls a function when hovered -->
<button onmouseover="highlight()">Hover over me</button>

<script>
function highlight() {
  // code runs when mouse moves over the button
}
</script>

Mouse events: onmouseover and onmouseout

onmouseover fires when the mouse pointer moves onto an element. onmouseout fires when the mouse pointer moves off the element. These independent events are often used together when a hover effect needs to be reversed:

<div id="box"
     onmouseover="turnYellow()"
     onmouseout="turnWhite()">
  Hover over this box
</div>

<script>
function turnYellow() {
  document.getElementById("box").style.backgroundColor = "yellow";
}
function turnWhite() {
  document.getElementById("box").style.backgroundColor = "white";
}
</script>
1 User hovers πŸ–± β†’ 2 Event fires onmouseover triggers β†’ 3 Function changeColour() called β†’ 4 getElementById finds the element β†’ 5 Style backgroundColor = "yellow" user action event function DOM lookup DOM change

Every JavaScript event follows this flow: user action β†’ event β†’ function β†’ DOM change

Targeting elements with document.getElementById()

document.getElementById("id") finds the element with that id and returns it so you can change its properties. The id value must be in quotes and must exactly match the id attribute in the HTML.

Once you have the element, you can change:

  • A style property: element.style.backgroundColor = "yellow"
  • The text content: element.innerHTML = "New text"

CSS properties with hyphens (like background-color) use camelCase when accessed through element.style, so the equivalent is element.style.backgroundColor. A hyphen cannot be used inside an identifier after a dot because JavaScript treats it as subtraction. Hyphenated property names can exist elsewhere in JavaScript, but they must be accessed with bracket notation, such as object["background-color"].

CSS property JavaScript equivalent
background-colorstyle.backgroundColor
colorstyle.color
font-sizestyle.fontSize
border-radiusstyle.borderRadius
displaystyle.display

Changing text with innerHTML

innerHTML lets you replace the text (or HTML) inside an element. This can update a message when the pointer moves onto an element and restore it when the pointer moves away:

<p id="msg"
   onmouseover="showMessage()"
   onmouseout="restoreMessage()">Hover over me.</p>

<script>
function showMessage() {
  document.getElementById("msg").innerHTML = "Hello, world!";
}
function restoreMessage() {
  document.getElementById("msg").innerHTML = "Hover over me.";
}
</script>

A mouse event handler can call a named JavaScript function. Define the function inside the <script> block:

function functionName() {
  // code to run goes here
}

In onmouseover or onmouseout, write the function name followed by (). The brackets tell JavaScript to run it:

<button onmouseover="highlight()">Hover</button>  <!-- correct: with () -->
<button onmouseover="highlight">Hover</button>    <!-- wrong: missing () -->

Worked examples

Example 1 β€” Mouseover colour change on a div

Write a <div> that turns yellow when the mouse moves over it and returns to white when the mouse leaves.

1
Give the <div> an id so JavaScript can find it, and add onmouseover and onmouseout event handlers calling two functions.
2
Write the two functions in a <script> block. Each function uses document.getElementById() to find the div and changes its style.backgroundColor.
3
Note: CSS uses background-color (hyphen); JavaScript uses backgroundColor (camelCase).
<div id="box"
     onmouseover="turnYellow()"
     onmouseout="turnWhite()"
     style="padding:1rem;border:1px solid #ccc;">
  Hover over me
</div>

<script>
function turnYellow() {
  document.getElementById("box").style.backgroundColor = "yellow";
}
function turnWhite() {
  document.getElementById("box").style.backgroundColor = "white";
}
</script>
Example 2 β€” Mouseover text change with innerHTML

Write a paragraph that changes from "Hover over me." to "Hello, world!" when the mouse moves over it, then restores the original text when the mouse leaves.

1
Give the <p> element an id of "msg" so the functions can find it.
2
Add onmouseover and onmouseout handlers that call the two functions.
3
Use document.getElementById("msg").innerHTML in each function to set or restore the text.
<p id="msg"
   onmouseover="showMessage()"
   onmouseout="restoreMessage()">Hover over me.</p>

<script>
function showMessage() {
  document.getElementById("msg").innerHTML = "Hello, world!";
}
function restoreMessage() {
  document.getElementById("msg").innerHTML = "Hover over me.";
}
</script>
Example 3 β€” Image rollover effect

Create an image that swaps to a different image on onmouseover and reverts on onmouseout. This is how early rollover navigation menus worked β€” the original web standard for interactive nav images before CSS :hover was widely supported.

1
Give the <img> element an id so JavaScript can find it.
2
In the onmouseover function, change the src attribute to the hover image. In onmouseout, set it back to the original image.
3
The src property is accessed via element.src β€” no .style needed here because src is an HTML attribute, not a CSS property.
<img id="logo"
     src="logo_normal.png"
     alt="School logo"
     onmouseover="swapIn()"
     onmouseout="swapOut()">

<script>
function swapIn() {
  document.getElementById("logo").src = "logo_hover.png";
}
function swapOut() {
  document.getElementById("logo").src = "logo_normal.png";
}
</script>

Before CSS :hover was widely supported, this image-swap technique was how web designers built interactive navigation menus. It is less common now but still examined at N5.

Now you try

Write a paragraph element with id="highlight" and text "Hover over me". The paragraph should:

  • Change its backgroundColor to #E6F1FB when the mouse moves over it (onmouseover)
  • Return to transparent when the mouse moves away (onmouseout)

Show the HTML element with its event handlers, and the two JavaScript functions.

<p id="highlight"
   onmouseover="addHighlight()"
   onmouseout="removeHighlight()">Hover over me</p>

<script>
function addHighlight() {
  document.getElementById("highlight").style.backgroundColor = "#E6F1FB";
}
function removeHighlight() {
  document.getElementById("highlight").style.backgroundColor = "transparent";
}
</script>

Key points: the id in getElementById must match the id attribute exactly; use backgroundColor (camelCase) not background-color; the value must be in quotes.

Common mistakes
βœ•
Capital D in getElementById β€” writing getElementByID instead. JavaScript is case-sensitive. getElementById has a lowercase d at the end. Writing ID (capital) causes an error and the code will not run. This is the single most common JavaScript typo at N5 level.
βœ•
Forgetting quotes around the value: style.backgroundColor = red fails because red is treated as a variable name, not a colour string. All CSS values in JavaScript must be in quotes: style.backgroundColor = "red".
βœ•
Using CSS hyphen syntax in JavaScript: style.background-color is invalid in JavaScript. The hyphen means "subtract". All multi-word CSS properties become camelCase in JavaScript: background-color β†’ backgroundColor, font-size β†’ fontSize, border-radius β†’ borderRadius.
βœ•
Missing the () when calling a function in an event handler: onmouseover="highlight" does nothing β€” JavaScript sees it as referring to the function object, not calling it. Always include the brackets: onmouseover="highlight()".
Exam tip

The N5 exam tests JavaScript in two main ways: (1) you are shown a function and asked to predict what happens β€” read the event handler to find which event triggers it, then trace the function to see what property changes on which element. (2) You are shown broken code and asked to identify and fix the error β€” always check: is getElementById spelled correctly? Is the value in quotes? Is the property camelCase? Are the brackets present in the event handler?

A strong 2-mark answer when asked "what happens when the user hovers over the button?": "The onmouseover event fires and the named function is called (1 mark). The function uses document.getElementById() to find the target element and changes its style property / innerHTML (1 mark)."

Task Set

Questions 1–4 are auto-checked. Questions 5–10 are self-marked β€” write your answer, then reveal the model answer to check your work.

1. Which JavaScript event fires when the mouse pointer leaves an element? TYPE 1

2. What does element.innerHTML = "Welcome!" do? TYPE 1

3. What does document.getElementById("banner") return? TYPE 1

4. Which of these is the correct syntax for an onmouseover event handler? TYPE 1

5. Write the HTML and JavaScript to make a <div id="banner"> change its text to "Welcome!" when the mouse enters, and back to "Hover over me" when the mouse leaves. (3 marks) TYPE 2

<div id="banner"
     onmouseover="showWelcome()"
     onmouseout="showDefault()">
  Hover over me
</div>

<script>
function showWelcome() {
  document.getElementById("banner").innerHTML = "Welcome!";
}
function showDefault() {
  document.getElementById("banner").innerHTML = "Hover over me";
}
</script>
Marks: correct HTML element with both event handlers (1); showWelcome() function correctly sets innerHTML to "Welcome!" (1); showDefault() function correctly restores original text (1).

6. Explain the difference between onmouseover and onmouseout. Give one example of when you would use each. (2 marks) TYPE 2

onmouseover fires when the mouse pointer moves onto an element. Example: changing a navigation item's background colour when the user hovers over it (1 mark).

onmouseout fires when the mouse pointer moves away from an element. Example: restoring the navigation item's original background colour when the pointer leaves (1 mark).

The events are independent, but they are often paired when a hover effect needs to be reversed.

7. Write a complete working example: a heading with id="title" that changes to red on onmouseover and returns to black on onmouseout. Include the HTML and both JavaScript functions. (3 marks) TYPE 2

<h1 id="title"
    onmouseover="makeRed()"
    onmouseout="makeBlack()">My Heading</h1>

<script>
function makeRed() {
  document.getElementById("title").style.color = "red";
}
function makeBlack() {
  document.getElementById("title").style.color = "black";
}
</script>
Marks: heading has the correct id and both event handlers (1); makeRed() sets style.color to "red" (1); makeBlack() restores it to "black" (1).

8. A pupil writes the following code. Identify the error and write the corrected version. (2 marks) TYPE 2
document.getElementByID("box").style.color = "blue";

Error: getElementByID has a capital D at the end. JavaScript is case-sensitive β€” the correct method name is getElementById with a lowercase d (1 mark).

Corrected code:
document.getElementById("box").style.color = "blue";
(1 mark for the correctly spelled corrected version)

9. Write the HTML and JavaScript for a navigation bar with two list items β€” "Home" and "About" β€” where each item changes its background colour to #E6F1FB on onmouseover and reverts to transparent on onmouseout. (3 marks) TYPE 2

<nav>
  <ul>
    <li id="nav-home"
        onmouseover="highlightHome()"
        onmouseout="clearHome()">Home</li>
    <li id="nav-about"
        onmouseover="highlightAbout()"
        onmouseout="clearAbout()">About</li>
  </ul>
</nav>

<script>
function highlightHome() {
  document.getElementById("nav-home").style.backgroundColor = "#E6F1FB";
}
function clearHome() {
  document.getElementById("nav-home").style.backgroundColor = "transparent";
}
function highlightAbout() {
  document.getElementById("nav-about").style.backgroundColor = "#E6F1FB";
}
function clearAbout() {
  document.getElementById("nav-about").style.backgroundColor = "transparent";
}
</script>
Marks: correct HTML structure with ids and both event handlers on each item (1); mouseover functions correctly set backgroundColor (1); mouseout functions correctly revert to transparent (1). Accept alternative approaches (e.g. passing this as a parameter) if syntactically correct.

10. Describe step by step what happens when a user hovers over a button that has onmouseover="highlight()". Start from "the user moves the mouse…" (3 marks) TYPE 2

1. The user moves the mouse pointer over the button β€” this triggers the onmouseover event on that element (1 mark).

2. The browser sees the onmouseover="highlight()" attribute and calls the highlight() JavaScript function (1 mark).

3. The function runs β€” it uses document.getElementById() to find the target element and updates its style property or innerHTML, immediately changing what the user sees (1 mark).
Teacher notes β€” Shift+T to hide

Suggested timing: Two periods (approx 3 hours). Period 1: JavaScript intro, onmouseover and onmouseout with style changes (Examples 1 and 3), Now you try, warm-up. Period 2: changing innerHTML and src with mouse events, task set Q5–Q10.

Opening demo β€” live DevTools: Open browser DevTools console on the projector. Type document.getElementById("theme-toggle").style.backgroundColor = "red" and press Enter. The theme button turns red instantly. This single demo shows pupils that JavaScript changes the live page. Then show it reverting. This is more motivating than any explanation.

Period 1 focus β€” mouseover/mouseout: Keep the first period entirely on the colour-change pattern. Every pupil should have a working mouseover example running in a file on their machine before the period ends. Introduce innerHTML and image changes in Period 2.

Case sensitivity: Write getElementById and getElementByID on the board side by side. Ask pupils to spot the difference. Then explain why it matters. This prevents Q8-style errors before they happen.

CamelCase: Show the CSS-to-JS conversion table from the notes on the projector. Give pupils 2 minutes to convert 5 CSS properties to JS equivalents (background-color, font-size, border-radius, text-align, font-weight). Quick written task, then check answers together.

Q8 (case-sensitive error) is a real SQA question type β€” worth spending 5 minutes discussing after pupils attempt it.