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

JavaScript Event Handlers

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


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.

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.

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!

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

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()">