Chin
Chin

Reputation: 12712

jquery turning "on" and "off" event handlers

How would I apply the "off" directive to a named handler?

ex

var $btn = $("#theBtn");
var namedHandler = $btn.on("click", function() {
//do something
//then turn off
})

would I turn it off like this

$btn.off("click");

or could I do something else now it is stored in a variable?

namedHandler.off("click");

or

namedHandler.off();

etc.

Any pointers much appreciated.

Upvotes: 21

Views: 34875

Answers (4)

user
user

Reputation: 18529

In addition to what @alex & @WereWolf said, I often find this useful :

For a single use event handler, you can use .one() instead of .on() followed by .off()

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
});

http://api.jquery.com/one/

Upvotes: 8

The Alpha
The Alpha

Reputation: 146191

You can also do this

function handleClick(event) 
{
    // code
}

$('#btn').on('click', handleClick);

$('#btn').off('click', handleClick);

Some usefull examples only about on/off here.

Upvotes: 13

alex
alex

Reputation: 490173

The same reference to the jQuery object will be in $btn and namedHandler. Both return a reference to the same thing so the assignment is assigning the same thing.

You could turn it off() with either method.

What may be more suited to your example is namespacing your event, so off('click', ...) won't unbind all click events.

Upvotes: 12

Andreas Wong
Andreas Wong

Reputation: 60516

You could define a function for your handler and pass it to .off() to disable that handler and .on() to reenable it.

The documentation provides examples to achieve this

http://api.jquery.com/off/

function aClick() {
  $("div").show().fadeOut("slow");
}
$("#bind").click(function () {
  $("body").on("click", "#theone", aClick)
    .find("#theone").text("Can Click!");
});
$("#unbind").click(function () {
  $("body").off("click", "#theone", aClick)
    .find("#theone").text("Does nothing...");
});

Upvotes: 2

Related Questions