Episode 15 of 24
Binding and Unbinding Events
Learn how to attach and remove event handlers with jQuery on() and off().
jQuery provides the .on() method to attach event handlers and .off() to remove them.
on() — Attach Events
// Click event
$("button").on("click", function() {
console.log("Button clicked!");
});
// Multiple events on one element
$("input").on("focus", function() {
$(this).css("border-color", "#3498db");
}).on("blur", function() {
$(this).css("border-color", "#ddd");
});
Multiple Events, One Handler
$("input").on("focus blur", function() {
$(this).toggleClass("focused");
});
Event Delegation
Attach events to dynamically added elements:
// This works for elements added AFTER the event is bound
$("ul").on("click", "li", function() {
$(this).toggleClass("done");
});
// Now even new li elements will respond to clicks
$("ul").append("<li>New item</li>");
off() — Remove Events
// Remove all click handlers
$("button").off("click");
// Remove a specific handler
function handleClick() {
console.log("Clicked!");
}
$("button").on("click", handleClick);
$("button").off("click", handleClick);
one() — Run Once
// Handler runs only ONCE, then auto-removes
$("button").one("click", function() {
console.log("This only fires once!");
$(this).prop("disabled", true);
});
Practical Example
// Disable button after form submit
$("form").on("submit", function(e) {
e.preventDefault();
let $btn = $(this).find("button[type='submit']");
$btn.prop("disabled", true).text("Submitting...");
// Simulate async operation
setTimeout(function() {
$btn.prop("disabled", false).text("Submit");
}, 2000);
});