To react to events in JavaScript, we first need to associate an event handler that will execute when the event occurs.
That is, we must define a function that we want to be triggered when the event happens. And, somehow, we have to associate this function with the event.
This can be done in several ways:
| Method | Flexibility | Logic Separation |
|---|---|---|
| Inline Attribute ❌ | Low | Poor |
| Element Property ❌ | Medium (overwrites others) | Medium |
addEventListener Method 💚 | High | High |
The recommended one 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 myFunction function will execute when the user clicks the button.
Advantages:
- Very simple
Disadvantages:
- Difficulty 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");
};
Advantages:
- More organized and cleaner than the previous one.
Disadvantages:
- Does not allow adding multiple handlers for the same event.
addEventListener Method
The most modern and flexible method for associating 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");
});
Advantages:
- Allows adding multiple handlers for the same event.
- Supports additional options, like using the event in capture or bubble mode.
- Follows best practices for modern programming.
Use addEventListener whenever possible.
The addEventListener Method
The addEventListener method is the modern and preferred approach for adding 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 bubbling phase.
Types of Functions Associated with Events
When associating a function with an event, you can choose anonymous functions, pre-defined functions, or even arrow functions.
An anonymous function is defined directly where the event handler is assigned. It’s 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 the event handler needs to be reused.
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 - It responds to clicks on any
liinside it.
