Summary: in this tutorial, you will learn about JavaScript events, event models, and how to handle events.
Introduction to JavaScript Events
In JavaScript, an event is something that happens in the browser. For example:
- Click a button
- Moving the mouse
- Loading a page
You can react to events by running a function when the event occurs. The function is called an event handler (or listener).
Suppose you have a button with the id btn:
<button id="btn">Click Me!</button>Code language: HTML, XML (xml)To define a function that executes when the button is clicked, you can register an event handler using the addEventListener() method:
let btn = document.querySelector('#btn');
function handleClick() {
alert('It was clicked!');
}
btn.addEventListener('click', handleClick);Code language: JavaScript (javascript)How it works.
- First, select the button with the id
btnby using thequerySelector()method. - Second, define a function called
handleClick()as an event handler. - Third, register an event handler using the
addEventListener()so that when you click the button, thedisplay()function will execute.
A shorter way to register an event handler is to place all code in an anonymous function, like this:
let btn = document.querySelector('#btn');
btn.addEventListener('click',function() {
alert('It was clicked!');
});Code language: JavaScript (javascript)Alternatively, you can use an arrow function:
let btn = document.querySelector('#btn');
btn.addEventListener('click',() => {
alert('It was clicked!');
});Code language: JavaScript (javascript)Event flow
Assuming that you have the following HTML document:
<!DOCTYPE html>
<html>
<head>
<title>JS Event Demo</title>
</head>
<body>
<div id="container">
<button id='btn'>Click Me!</button>
</div>
</body>Code language: HTML, XML (xml)When you click the button, the event can move through the page.
Event bubbling
In the event bubbling model, an event starts at the most specific element and then flows upward toward the least specific element (the document or even window).
When you click the button, the click event occurs in the following order:
- button
- div with the id container
- body
- html
- document
The click event first occurs on the button which is the element that was clicked. Then the click event goes up the DOM tree, firing on each node along its way until it reaches the document object.
The following picture illustrates the event bubbling effect when users click the button: