最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

input - Disable keyboard shortcuts when text field or textarea has focus using pure JavaScript - Stack Overflow

programmeradmin5浏览0评论

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!

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!

Share Improve this question asked Nov 27, 2013 at 21:42 any_hany_h 5783 gold badges10 silver badges29 bronze badges 2
  • The best way would be to not listen to the document, but to the pagination links for the keyup. – kennebec Commented Nov 27, 2013 at 21:53
  • 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. – any_h Commented Nov 28, 2013 at 9:52
Add a ment  | 

2 Answers 2

Reset to default 5

Disable event propagation of the input to the document

nextEl.onkeyup = prevEl.onkeyup = function(e){ e.stopPropagation(); };

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,
  )
发布评论

评论列表(0)

  1. 暂无评论