← Back to Chapters

jQuery on() & off()

? jQuery on() & off()

? Quick Overview

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().

? Key Concepts

  • on() attaches one or more events to elements
  • off() removes previously attached events
  • Supports multiple events at once
  • Works with event delegation
  • Helps avoid memory leaks

? Syntax / Theory

Basic Syntax:

? View Code Example
// Attaching an event using on()
$(selector).on(event, function);

// Removing an event using off()
$(selector).off(event);

? Code Example(s)

? View Code Example
// Attach and remove click event using on() and off()
$("#btnOn").on("click", function(){
alert("Button Clicked");
});

$("#btnOff").on("click", function(){
$("#btnOn").off("click");
});

? Live Output / Explanation

?️ What Happens?

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.

? Interactive Example

Try clicking the buttons below to understand how events are attached and removed dynamically.

? View Code Example
// Interactive demo using on() and off()
$("#demoOn").on("click", function(){
  $(this).text("Clicked!");
});

$("#demoOff").on("click", function(){
  $("#demoOn").off("click");
  $("#demoOn").text("Click Disabled ?");
});

? Live Playground: The Light Switch

This interactive diagram visualizes if the event listener is currently "wired" or "cut".

1. Control the Wiring

Wiring Status: Disconnected

2. Test the Object

...

? Use Cases

  • Dynamic elements loaded after page load
  • Event delegation in lists and tables
  • Enabling and disabling user interactions
  • Improving performance by managing events

✅ Tips & Best Practices

  • Always prefer on() over old event methods
  • Use event delegation for dynamically added elements
  • Remove unused events using off()
  • Keep event logic clean and minimal

? Try It Yourself

  • Create a button that changes color on hover using on()
  • Remove the hover effect using off()
  • Attach multiple events like click and double-click
  • Practice event delegation with a list