The on() and off() methods in jQuery are used to attach and remove event handlers. They are the modern and recommended way to handle events, replacing older methods like .click(), .bind(), and .unbind().
Basic Syntax:
// Attaching an event using on()
$(selector).on(event, function);
// Removing an event using off()
$(selector).off(event);
// Attach and remove click event using on() and off()
$("#btnOn").on("click", function(){
alert("Button Clicked");
});
$("#btnOff").on("click", function(){
$("#btnOn").off("click");
});
When the first button is clicked, an alert message appears. Clicking the second button removes the click event, so further clicks on the first button do nothing.
Try clicking the buttons below to understand how events are attached and removed dynamically.
// Interactive demo using on() and off()
$("#demoOn").on("click", function(){
$(this).text("Clicked!");
});
$("#demoOff").on("click", function(){
$("#demoOn").off("click");
$("#demoOn").text("Click Disabled ?");
});
This interactive diagram visualizes if the event listener is currently "wired" or "cut".
on() over old event methodsoff()on()off()