Chapter 1 deck Chapter 2 deck Chapter 3 deck Chapter 4 deck Chapter 5 deck Chapter 6 deck Chapter 7 deck Chapter 8 deck Chapter 9 deck Chapter 10 deck Chapter 11 deck Chapter 12 deck Chapter 13 deck Chapter 14 deck

JavaScript Event Handlers

5 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 5 deck

JavaScript Event Handlers
Fullscreen for presentation · Print / PDF for a handout
1 / 5
Lesson

JavaScript Event Handlers

Making pages respond to clicks, loads, submissions and other events.

JavaScript Event Handlers

Event Handlers

JavaScript is event-driven. An event handler is a piece of code triggered in response to a specific user or browser action.

EventWhen it fires
clickUser clicks an HTML element.
load / unloadBrowser finishes or starts loading a page.
submitUser submits a form.
mouseover / mouseoutMouse enters or leaves an element.
keydown / keyupUser presses or releases a keyboard key.
changeValue of an input element changes.
JavaScript Event Handlers

What Event Handlers Can Do

  • Page load actions — initialise components, start timers, load data.
  • Page close actions — cleanup when the user navigates away.
  • Button click actions — submit forms, trigger animations.
  • Form input validation — verify data in real time before it is sent to the server.
  • DOM manipulation — show/hide elements, change text, update styles dynamically.
JavaScript Event Handlers

Event Handler Example

<html>
<body>
  <button onclick="myFunction()">Click Me</button>
  <p id="demo"></p>

  <script>
    function myFunction() {
      document.getElementById("demo").innerHTML = "Welcome to the JavaScript class!";
    }
  </script>
</body>
</html>

When the user clicks the button, the browser calls myFunction(), which finds the element with id="demo" and sets its innerHTML. The page updates instantly — no reload needed!

JavaScript Event Handlers

Activity — complete the code

Complete the event handler example.

<button ="myFunction()">Click Me</button>
<p id="demo"></p>
 
<script>
function myFunction() {
document.getElementById("demo"). = "Welcome!";
}
</script>
 
<!-- Fires when the user presses a key -->
<input on="checkKey()">