Language: EN

javascript-add-event-handlers

How to Add Event Handlers in JavaScript

To react to events in JavaScript, we must first associate it with an event handler that will execute when the event occurs.

That is, we need to define a function that we want to trigger when the event happens. And somehow, we have to associate this function with the event.

This can be done in several ways:

MethodFlexibilitySeparation of logic
Inline attribute ❌LowPoor
Element property ❌Medium (overrides others)Medium
addEventListener method 💚HighHigh

The recommendation is addEventListener. But let’s look at each of them,

Inline attribute in HTML

One of the simplest ways to add an event is directly in the HTML using the onclick attribute or any other event attribute.

This method is mainly used for events like click, mouseover, keydown, etc.

<button onclick="myFunction()">Click here</button>

In this example, the function myFunction will execute when the user clicks the button.

Disadvantages:

  • Difficulty in separating JavaScript logic from HTML markup.

Element property

Another way is to assign a function directly to the event property of a DOM element.

const button = document.getElementById("myButton");

button.onclick = function () {
    alert("Button clicked");
};

Disadvantages:

  • Does not allow adding multiple handlers for the same event.

addEventListener Method

The most modern and flexible method to associate functions with events is addEventListener. This method allows adding multiple functions to the same event.

const button = document.getElementById("myButton");

button.addEventListener("click", function () {
    alert("Button clicked with addEventListener");
});

Use addEventListener whenever possible.

The addEventListener method

The addEventListener method is the modern and preferred approach to add events to DOM elements.

This method has several advantages, such as allowing multiple event handlers to be added to a single element, and we can also remove the event handler later.

Its usage is as follows,

element.addEventListener('eventType', handlerFunction, [options]);
  • element: The HTML element to which the event handler will be added.
  • eventType: The type of event to listen for (e.g., 'click', 'submit', 'keydown').
  • handlerFunction: The function that will execute when the event occurs.
  • options (optional): An object that can specify whether the event should be captured during the capture or bubble phase.

Types of Functions Associated with Events

When associating a function with an event, you can choose between anonymous functions, previously defined functions, or even arrow functions.

An anonymous function is defined directly where the event handler is assigned. It is useful for handling simple events.

button.addEventListener('click', function() {
    console.log('Button clicked!');
});

A named function is a function that has a name and can be defined separately. This is useful for handling more complex events and when you need to reuse the event handler.

function handleClick() {
    console.log('Button clicked!');
}

button.addEventListener('click', handleClick);

Arrow functions provide a more concise syntax and do not have their own this context, which can be useful in certain cases.

button.addEventListener('click', () => {
    console.log('Button clicked!');
});

Event Delegation

Event delegation is an advanced technique that allows handling events on child elements using a single handler on a parent element.

This is useful when you have dynamically generated elements or a large number of similar elements.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Event Delegation</title>
</head>
<body>
    <ul id="myList">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>

    <script>
        document.getElementById('myList').addEventListener('click', function(event) {
            if (event.target.tagName === 'LI') {
                alert('List item clicked: ' + event.target.textContent);
            }
        });
    </script>
</body>
</html>

In this example,

  • The event handler is assigned to the ul
  • Responds to clicks on any li within it.