Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove events with jquery or javascript

I have this:

$(function(){
    //remove keydown doSomething2
    $("body").keydown(doSomething1);
});

In other view I have this:

$(function(){
    //remove keydown doSomething1
    $("body").keydown(doSomething2);
});

How to do what's in the comment? With my current code, both doSomething1 and doSomething2 are called. I want do disabled the one I dont need.

like image 747
petko_stankoski Avatar asked Aug 03 '12 13:08

petko_stankoski


2 Answers

To remove an event listener with jQuery, you can use .off():

$("body").off("keydown", doSomething2);

Remember the keydown method is just a shortcut for .on("keydown", ...).

However, to "disable" them it might be easier to have only one handler that executes different things based on the current selected view, or have both of them bound and each with a short check that the right view is currently selected.

like image 139
Bergi Avatar answered Oct 29 '22 17:10

Bergi


If doSomething2 is a function reference, you can use .off() (jQuery 1.7+) or .unbind() to remove jQuery bound event handlers:

$('body').off('keydown', doSomething2);

// or

$('body').unbind('keydown', doSomething2);

Note that execution order will be a factor. If the code to unbind the event handler is run first it will have no effect. In general, jQuery event handlers are triggered in the order they're bound, so if the first code snippet in your question is executed first, this approach won't work (you'll need to re-order it).

like image 4
Anthony Grist Avatar answered Oct 29 '22 17:10

Anthony Grist