Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a specific event callback from an HTML element with jquery?

I have an element in a webpage which has several callbacks on it

// First callback
$("#element").click(fn1);

// Second callback
$("#element").click(fn2);

// Definitions
function fn1(){console.log("1");}
function fn2(){console.log("2");}

Is there a way to remove only fn2 from the list of callbacks triggered by jQuery. I know I could add an 'if' inside the function and some global variable, but that's not what I'm looking for.

like image 820
malber Avatar asked Mar 12 '13 09:03

malber


3 Answers

The second parameter in the unbind function specifies the handler to unbind.

$("#element").unbind("click", fn2);

Working Example: http://jsfiddle.net/k73Nx/

like image 151
Kevin Bowersox Avatar answered Oct 21 '22 15:10

Kevin Bowersox


Interesting that nobody mentioned namespaces yet. Is there a reason for that?

When attaching your event, you can namespace it. Instead of $(elem).on('click', fn) you would add a namespace to the click event. $(elem).on('click.namespaced', fn)

When unbindung, you can then unbind that exact event, using the namespace as well. $(elem).off('click.namespaced')

This is most practical when you're defining your event function inline.

One more thing you can do with namespaces is to unbind all event types within a namespae with just a single call: $(elem).off('.namespaced')

like image 4
MildlySerious Avatar answered Oct 21 '22 17:10

MildlySerious


Be careful with your syntax here, other answers are very loose with theirs.

If you use:

$('#element').on('click',function() {
 //callback code
});

Then you must use:

$('#element').off('click');

You cannot use

$('body').off('click','#element',function() { }); 

or

$(document).off('click','#element',function() { }); 

because you originally bound your event to #element, not to document or body.

like image 1
Adam Avatar answered Oct 21 '22 17:10

Adam