user695868
user695868

Reputation:

keydown only when input is not in focus

Currently I've setup a function to go forward and back when pressing the left and right arrow keys in pages using this:

$(document).keydown(function (e) {
    if ($(e.target).is('input')) { return false
    } else if (e.keyCode == 37) {
        $(".pageback").click();
        return false;
    }
    if (e.keyCode == 39) {
        $(".pagenext").click();
        return false;
    }
});

This allows the arrow keys to be used to browse back and forth, but when a textbox is encountered, the arrow keys are still active.

Although this stops the keydown functions when the textbox is in focus, it also does not allow anything at all to be typed into the input area.

HELP!

Thanks

Upvotes: 9

Views: 6050

Answers (2)

Abhi Beckert
Abhi Beckert

Reputation: 33349

My approach is to check if the target is document.body on keydown, then wait for keyup.

document.addEventListener('keydown', function(keyEvent) {
  if (keyEvent.key != 'ArrowLeft' || keyEvent.shiftKey || keyEvent.ctrlKey || keyEvent.altKey || keyEvent.metaKey) {
    return
  }
  if (keyEvent.target != document.body) {
    return
  }
  
  keyEvent.preventDefault()
  
  // myButton.classList.add('active') // visual feedback a button has been triggered

  document.addEventListener('keyup', function(keyEvent) {
    keyEvent.preventDefault()
    
    // do your stuff
  })
})

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150010

"it also does not allow anything at all to be typed into the input area."

The problem is this part:

if ($(e.target).is('input')) { return false

When you return false from the event handler it prevents the default behaviour for the event.

Change it to return true or just return (with no value) and the default behaviour (in this case, typing in the field) will be permitted.

(Note: you may also want to check for textarea elements, not just inputs.)

Upvotes: 11

Related Questions