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.
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.
Share Improve this question asked Aug 3, 2012 at 13:25 petko_stankoskipetko_stankoski 10.7k42 gold badges134 silver badges234 bronze badges 1- I recommend keeping the event handler and add a variable that tells what do do when a key is pressed. – Anders Lindén Commented Aug 3, 2012 at 13:31
3 Answers
Reset to default 10To 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.
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).
try this as below using jQuery:
$(function(){
// this would remove keydown from body
$("body").unbind('keydown', doSomething2);
});