Reputation: 2188
I want to prevent only some actions of key presses on a webpage. Specifically backspace. Normally, I would do something like this:
function keyPress(ev) {
if(ev.keyCode === 8) {
ev.preventDefault();
}
// do cool stuff here
}
$(document).keydown(keyPress);
That code prevents all the default actions backspace does. I want to prevent it from navigating to the last page, but I want to allow it to delete characters in text fields. How do I prevent only from navigating but not from text manipulation?
Upvotes: 1
Views: 124
Reputation: 418
For the specific case you mention you could just check if the user has a text field focused, and if so, not prevent default.
function keyPress(ev) {
var targetElTag = document.activeElement.tagName;
if (ev.keyCode === 8 && targetElTag !== 'TEXTAREA') {
ev.preventDefault();
}
}
You would also want to include any other focusable elements you wanted backspace to function on.
Upvotes: 1