Reputation: 49510
I want to remove all event listeners currently attached to a key board key using javascript. I know It's possible for HTML elements by cloning and replacing that particular element but how to do it for a key?
For example pressing Q
in Reddit opens the dropdown so how can I prevent it?
Things I tried but didn't work:
onkeydown = function(e){
if(e.key == 'q'){
e.preventDefault()
e.stopImmediatePropagation()
e.stopPropagation()
}
}
onkeyup = function(e){
if(e.key == 'q'){
e.preventDefault()
e.stopImmediatePropagation()
e.stopPropagation()
}
}
Upvotes: 2
Views: 1165
Reputation: 49510
Found a workaround by executing event handler in the capturing phase i.e. setting useCapture
to true.
window.addEventListener('keyup', function (e) {
if(e.key == 'q'){
e.stopImmediatePropagation()
}
}, true); //useCapture
Please do post if there are any better solutions.
Upvotes: 2