Attach Multiple Event Handlers Using jQuery on()
The jQuery .on() method is the standard way to attach
event listeners to DOM elements, offering flexibility to bind multiple
events simultaneously. This guide covers how to bind several events to
an element using two primary patterns: sharing a single callback across
multiple event triggers, and mapping distinct functions to different
events using object notation, including how to handle event
delegation.
1. Sharing a Single Handler Across Multiple Events
If you want multiple events (such as mouseenter and
mouseleave, or focus and blur) to
trigger the exact same function, pass each event name separated by a
space in the first argument of the .on() method.
$("#myElement").on("mouseenter mouseleave", function(event) {
if (event.type === "mouseenter") {
$(this).addClass("hovered");
} else if (event.type === "mouseleave") {
$(this).removeClass("hovered");
}
});Using the event.type property allows you to identify
which specific event triggered the callback if conditional logic is
required.
2. Attaching Different Handlers Using a Plain Object
When you need to execute different logic for different events on the
same element, pass a plain JavaScript object to .on(). The
object's keys represent the event names, and the values are their
corresponding callback functions.
$("#myElement").on({
click: function() {
console.log("Element clicked!");
},
mouseenter: function() {
$(this).css("background-color", "yellow");
},
mouseleave: function() {
$(this).css("background-color", "transparent");
}
});This syntax keeps code organized and eliminates the need to chain
multiple individual .on() calls together.
3. Combining Multiple Events with Event Delegation
Event delegation allows you to bind events to dynamic elements that may be added to the DOM after the initial page load. Both space-separated events and object mappings support delegation by providing a child selector.
For space-separated events sharing a handler:
$("#parentContainer").on("focus blur", "input.text-field", function() {
$(this).toggleClass("active");
});For distinct handlers using an object:
$("#parentContainer").on({
click: function() {
$(this).toggleClass("selected");
},
dblclick: function() {
$(this).remove();
}
}, ".child-item");In the object-based approach, the child selector is provided as the second argument after the event map, ensuring optimal performance and dynamic binding for all current and future child elements.