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.
| Event | When it fires |
|---|---|
click | User clicks an HTML element. |
load / unload | Browser finishes or starts loading a page. |
submit | User submits a form. |
mouseover / mouseout | Mouse enters or leaves an element. |
keydown / keyup | User presses or releases a keyboard key. |
change | Value 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()">