Event delegation in jQuery is a technique that allows us to handle events efficiently. Instead of adding event handlers to specific nodes, we can add a single event handler to a parent element.
In this tutorial, we aim to understand how to use event delegation effectively in jQuery.
By the end of this tutorial, you should be able to understand:
Before diving into this tutorial, you should have a basic understanding of:
Event delegation allows us to attach a single event listener to a parent element that will fire for all descendants matching a selector, whether they exist now or are added in the future.
This is achieved using two main jQuery methods: .on() for attaching event handlers, and .off() for removing them.
The .on() method attaches one or more event handlers for specified elements. The syntax is as follows:
$(selector).on(event, childSelector, data, function)
The .off() method removes event handlers that were attached with .on(). The syntax is as follows:
$(selector).off(event, childSelector, function)
Here is a practical example of event delegation in jQuery:
Example 1: Using .on()
// HTML
<div id="parent">
<button class="child">Click me!</button>
</div>
// jQuery
$('#parent').on('click', '.child', function() {
console.log('Button clicked!');
});
In this example, we are attaching a click event listener to the #parent element, which will fire for all .child elements. When you click on the button, it logs "Button clicked!" to the console.
Example 2: Using .off()
// HTML
<div id="parent">
<button class="child">Click me!</button>
</div>
// jQuery
$('#parent').on('click', '.child', function() {
console.log('Button clicked!');
});
// After some time...
$('#parent').off('click', '.child');
In this example, we first attach an event listener as before. Then, we remove the event listener using .off(). After this, clicking the button will no longer log anything to the console.
In this tutorial, we've covered the following points:
.on() and .off() methods.The next step in your learning journey could be to dive deeper into jQuery and explore other advanced topics such as AJAX, animations, and plugins.
Exercise 1:
Create an unordered list with three items. Attach a click event to the list that logs the text of the clicked list item.
Exercise 2:
Add a button that adds a new item to the list. The click event should still work for these new items.
Exercise 3:
Add a button that removes all event listeners from the list items.
When working on these exercises, remember to use event delegation and the .on() and .off() methods. Happy coding!