Disable keyboard shortcuts when text field or textarea has focus using pure JavaScript
Asked Answered
B

2

8

I have a simple script that uses left and right arrows to move to next and previous blogpost.

var nextEl = document.getElementById("pagination__next__link");
var prevEl = document.getElementById("pagination__prev__link");

document.onkeyup = function(e) {

    if (nextEl !== null) {
        if (e.keyCode === 37) {
            window.location.href = nextEl.getAttribute('href');
        }
    }
    if (prevEl !== null) {
        if (e.keyCode === 39) {
            window.location.href = prevEl.getAttribute('href');
        }
    }
    return false;
};

But it also works when I have text input or textarea focused. What would be the best way to disable the keyboard shortcuts when focused?

Thanks!

Bischoff answered 27/11, 2013 at 21:42 Comment(2)
The best way would be to not listen to the document, but to the pagination links for the keyup.Movie
You mean like @Thanh suggested below? nextEl.onkeyup = prevEl.onkeyup = function(e) {...} i can't really get it work... Have to listen to the document.Bischoff
I
5

Disable event propagation of the input to the document

nextEl.onkeyup = prevEl.onkeyup = function(e){ e.stopPropagation(); };
Impassion answered 27/11, 2013 at 22:2 Comment(0)
D
1

To adress the issue for all text inputs and textareas, I ended up using the following snippet of code:

  // prevent shortcuts from interfering with typing in text inputs or textareas
  document.documentElement.addEventListener(
    "keydown",
    (ev) => {
      if (
        ev.target &&
        (ev.target instanceof HTMLTextAreaElement ||
          (ev.target instanceof HTMLInputElement && (!ev.target.type || ev.target.type === "text")))
      ) {
        ev.stopPropagation()
      }
    },
    true,
  )
Dania answered 14/5, 2023 at 0:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.