The .on() method is the most important event-related function in modern jQuery.
While methods like .click() are great for simple tasks, .on()
provides a unified way to handle any event with advanced features like **event
delegation** and **multi-event binding**.
The simplest use of .on() works exactly like the specialized event methods:
$(selector).on("event", function() {
// Code to run
});
For example, a simple click event using .on():
$("button").on("click", function() {
$(this).hide();
});
This is where .on() truly shines. Imagine you have a list where you
dynamically add new items via AJAX. A regular .click() handler won't work
for the new items because they didn't exist when the script loaded. **Event
delegation** solves this!
Instead of attaching the event to the children (which might change), you attach it to a parent element that stays on the page, and specify which children to target.
// Syntax for Event Delegation
$(parentSelector).on("event", "childSelector", function() {
// This works even for future/dynamic children!
});
// Real Example
$("ul").on("click", "li", function() {
$(this).css("color", "blue");
});
You can use .on() to attach multiple event handlers to the same element
using an object syntax. This keeps your code clean and organized.
$("div").on({
mouseenter: function() {
$(this).addClass("highlight");
},
mouseleave: function() {
$(this).removeClass("highlight");
},
click: function() {
$(this).fadeOut();
}
});
| Feature | .click() | .on("click") |
|---|---|---|
| Ease of use | ✅ Very simple | ✅ simple |
| Dynamic Elements | ❌ No | ✅ Yes (Delegation) |
| Multiple Events | ❌ No | ✅ Yes (Object syntax) |
| Memory Efficiency | ⚠️ Average | ✅ Higher (one parent handler) |
With .on(), you aren't limited to standard events like click or hover. You
can listen for **custom events** that you trigger yourself using .trigger().
// Listening for a custom event
$(document).on("userLoggedIn", function() {
console.log("Welcome back, User!");
});
// Triggering the custom event somewhere else
$(document).trigger("userLoggedIn");
.on() as your default event handler. It's more flexible and leads to
better performance in complex applications.
document or a container div)..on()..on(), use the
.off() method.