BoltKey
BoltKey

Reputation: 2188

How do I prevent only specific default actions of key press on a page?

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

Answers (1)

Andrew G.
Andrew G.

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

Related Questions