JavaScript Events

Introduction to JavaScript events

An event is an action that occurs in the web browser, which the web browser feedbacks to you so that you can respond to it.

For example, when users click a button on a webpage, you may want to respond to this click event by displaying a dialog box.

Each event may have an event handler which is a block of code that will execute when the event occurs.

An event handler is also known as an event listener. It listens to the event and executes when the event occurs.

Suppose you have a button with the id btn:

<button id="btn">Click Me!</button>Code language: HTML, XML (xml)

To define the code that will be executed when the button is clicked, you need to register an event handler using the addEventListener() method:

let btn = document.querySelector('#btn');

function display() {
    alert('It was clicked!');
}

btn.addEventListener('click',display);Code language: JavaScript (javascript)

How it works.

  • First, select the button with the id btn by using the querySelector() method.

  • Then, define a function called display() as an event handler.

  • Finally, register an event handler using the addEventListener() so that when users click the button, the display() function will be executed.

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)

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, you’re clicking not only the button but also the button’s container, the div, and the whole webpage.

Event flow explains the order in which events are received on the page from the element where the event occurs and propagated through the DOM tree.

There are two main event models: event bubbling and event capturing.

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:

  1. button

  2. div with the id container

  3. body

  4. html

  5. 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:

Note that modern web browsers bubble the event up to the window object.

Event capturing

In the event capturing model, an event starts at the least specific element and flows downward toward the most specific element.

When you click the button, the click event occurs in the following order:

  1. document

  2. html

  3. body

  4. div with the id container

  5. button

The following picture illustrates the event capturing effect:

DOM Level 2 Event flow

DOM level 2 events specify that event flow has three phases:

  • First, event capturing occurs, which provides the opportunity to intercept the event.

  • Then, the actual target receives the event.

  • Finally, event bubbling occurs, which allows a final response to the event.

The following picture illustrates the DOM Level 2 event model when users click the button:

Event object

When the event occurs, the web browser passed an Event object to the event handler:

let btn = document.querySelector('#btn');

btn.addEventListener('click', function(event) {
    console.log(event.type);
});Code language: JavaScript (javascript)

Output:

'click'Code language: JavaScript (javascript)

The following table shows the most commonly-used properties and methods of the event object:

Note that the event object is only accessible inside the event handler. Once all the event handlers have been executed, the event object is automatically destroyed.

preventDefault()

To prevent the default behavior of an event, you use the preventDefault() method.

For example, when you click a link, the browser navigates you to the URL specified in the href attribute:

<a href="https://www.javascripttutorial.net/">JS Tutorial</a>Code language: HTML, XML (xml)

However, you can prevent this behavior by using the preventDefault() method of the event object:

let link = document.querySelector('a');

link.addEventListener('click',function(event) {
    console.log('clicked');
    event.preventDefault();
});Code language: JavaScript (javascript)

Note that the preventDefault() method does not stop the event from bubbling up the DOM. And an event can be canceled when its cancelable property is true.

stopPropagation()

The stopPropagation() method immediately stops the flow of an event through the DOM tree. However, it does not stop the browers default behavior.

See the following example:

let btn = document.querySelector('#btn');

btn.addEventListener('click', function(event) {
    console.log('The button was clicked!');
    event.stopPropagation();
});

document.body.addEventListener('click',function(event) {
    console.log('The body was clicked!');
});
Code language: JavaScript (javascript)

Without the stopPropagation() method, you would see two messages on the Console window.

However, the click event never reaches the body because the stopPropagation() was called on the click event handler of the button.

Summary

  • An event is an action that occurs in the web browser e.g., a mouse click.

  • Event flow has two main models: event bubbling and event capturing.

  • DOM Level 2 Event specifies that the event flow has three phases: event bubbling, the event occurs at the exact element, and event capturing.

  • Use addEventListener() to register an event that connects an event to an event listener

  • The event object is accessible only within the event listener.

  • Use preventDefault() method to prevent the default behavior of an event, but does not stop the event flow.

  • Use stopPropagation() method to stop the flow of an event through the DOM tree, but does not cancel the browser default behavior

Last updated