Event Binding with on()
In this page:
Basic on
on() is jQuery's general-purpose method for attaching any event handler to one or more matched elements, and is the modern replacement for older shortcut methods like .click() or .bind().
Example: Basic on
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
$("#btn").on("click", function() {
console.log("Clicked via on()");
});
</script>
</body>
</html>
Multiple Events with on
Passing an object of event-name/function pairs to on(), like $(button).on({click: fn1, mouseenter: fn2}), attaches several different handlers in a single call instead of chaining multiple .on() calls.
Example: Multiple Events with on
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Hover or click</button>
<script>
$("#btn").on({
click: function() { console.log("Clicked"); },
mouseenter: function() { console.log("Hovered"); }
});
</script>
</body>
</html>
Event Data
The handler function on() attaches automatically receives the event object as its first argument, giving you access to details like event.type or event.target without any extra setup.
Example: Event Data
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
$("#btn").on("click", function(event) {
console.log("Type:", event.type, "Target:", event.target.tagName);
});
</script>
</body>
</html>
Delegated on
Passing a selector string as on()'s second argument turns it into a delegated handler, letting one listener on a parent respond to events from any current or future descendant matching that selector.
Example: Delegated on
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list"><li>Item 1</li></ul>
<button id="add">Add Item</button>
<script>
$("#list").on("click", "li", function() {
console.log("Clicked:", $(this).text());
});
$("#add").on("click", function() {
$("#list").append("<li>New Item</li>");
});
</script>
</body>
</html>
Named Handlers
Assigning the handler to a named function, rather than an anonymous one, means you can later pass that same function reference to .off() to remove exactly that handler and no others.
Example: Named Handlers
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
function logClick() {
console.log("Named handler ran");
}
$("#btn").on("click", logClick);
</script>
</body>
</html>
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: