Removing events using jquery or javascript

I have it:

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

In another form, I have the following:

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

How to do what is in the comment? With my current code, both doSomething1 and doSomething2 are called. I want to disable the one that I do not need.

+5
source share
3 answers

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

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

Remember the method keydownis just a shortcut to .on("keydown", ...).

However, to “disable” them, it would be easier to have only one handler that does different things based on the currently selected view, or both are connected, and each with a short check that the correct view is currently selected.

+9
source

doSomething2 , .off() (jQuery 1.7+) .unbind() jQuery:

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

// or

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

, . , . jQuery , , , , ( ).

+4

try this as shown below using jQuery:

$(function(){
    // this would remove keydown from body
    $("body").unbind('keydown', doSomething2);
});
+4
source

All Articles