Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery turning "on" and "off" event handlers

Tags:

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.

like image 644
Chin Avatar asked Mar 29 '12 02:03

Chin


2 Answers

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.

like image 70
The Alpha Avatar answered Oct 05 '22 08:10

The Alpha


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.

like image 27
alex Avatar answered Oct 05 '22 10:10

alex