I have a keydown
event handler that I attach to my document so I can watch the keydown
event everywhere. However, after a condition is met, I want to be able to remove that and only that handler. How can I do this?
This is my current handler:
$(document).keydown(function(event){
console.log(event);
var tag = event.target.tagName.toLowerCase();
if(event.which = 27 && tag != 'input' && tag != 'textarea'){ //escape has been pressed
_dismissModal(modal_id);
}
});
I want to remove this keydown
event handler after _dismissModal
is called. How can I do this without removing all keydown
event handlers?
you can use jquery off() method. You also could put your keydown logic in to a separate function so you only can target that keydown action in your off method.
var mykeydownfunction= function(){
console.log(event);
var tag = event.target.tagName.toLowerCase();
if(event.which = 27 && tag != 'input' && tag != 'textarea'){ //escape has been pressed
_dismissModal(modal_id);
$(this).off('keydown', mykeydownfunction);// $(this) is the document
}
}
$(document).on('keydown', mykeydownfunction);
Use .off() to remove the event handler.
$(document).on("keydown", function(event){
console.log(event);
var tag = event.target.tagName.toLowerCase();
if(event.which = 27 && tag != 'input' && tag != 'textarea'){ //escape has been pressed
_dismissModal(modal_id);
$(this).off("keydown");
}
});
This has been answered already but using namespaces with removing events is really helpful and makes sure you don't cause any side effects.
// add click event with my.namespace as the namespace
$('element').on('click.my.namespace', function (e) {
// do something
});
// remove my.namespace click event from element
$('element').off('click.my.namespace');
You can open up the dev console and look at the events of an element with
$._data($('element')[0], 'events');
Open up the Object and you will see a click array. Expand your event and you will see the namespace actually shows up as
namespace.my
and not
my.namespace
http://api.jquery.com/on/
Search for Event names and namespaces for more info.
When the condition is met, use .off()
$(document).off('keydown');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With