Reputation: 400
I've checked this wonderful websites database and somehow provided answers does not work.
To prevent glitches, by default I must disable arrow keys and spacebar. That works with this code:
window.addEventListener("keydown", function(e) {
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);
But arrow keys and space bar are necessary for certain areas of website (input and textarea fields). To allow, I did as follows:
window.addEventListener("keydown", function(e) {
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) && ($(event.target)[0]!=$("textarea, input")[0])) {
e.preventDefault();
}
}, false);
But it does not seem to work. Help much appreciated!
Upvotes: 2
Views: 1798
Reputation: 19759
In this case, one option you have is setting an event handler for all the textarea
and input
elements and utilizing event.stopPropagation()
in order to prevent the window event handler from being fired. With this, the elements capture the keydown event and then tell the JavaScript engine not to fire other event handlers of elements that are higher in the DOM chain (such as the document or window).
window.addEventListener("keydown", function(e) {
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);
And with jQuery:
// Function gets run after document is loaded
$(function(){
$("textarea, input").keydown(function(e){
e.stopPropagation()
})
});
Edit: working jsFiddle.
Upvotes: 3
Reputation: 24435
You can get the targetted element name using the nodeName
property:
var targettedElement = $(event.target)[0].nodeName.toLowerCase(); // its uppercase by default
Then you can use that to check conditionally:
window.addEventListener("keydown", function(e) {
var targettedElement = $(event.target)[0].nodeName.toLowerCase();
if(
[32, 37, 38, 39, 40].indexOf(e.keyCode) > -1
&& targettedElement != 'textarea'
&& targettedElement != 'input'
) {
e.preventDefault();
}
}, false);
Upvotes: 1