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

keypress - Detect when the Tab-Key is pressed using Javascript - Stack Overflow

programmeradmin0浏览0评论

I would like to detect when the user clicks the tab key on their keyboard, using Javascript.

I've tried this:

document.onkeypress = (e) => {
    console.log(e);
}

And there it logges keys like letters, numbers and charcters, but not tab, ecs, backspace, enter or other keys like those.

Is there any way of doing so?

Edit: btw, I can only use pure Javascript for this project, no libraries like jQuery etc.

I would like to detect when the user clicks the tab key on their keyboard, using Javascript.

I've tried this:

document.onkeypress = (e) => {
    console.log(e);
}

And there it logges keys like letters, numbers and charcters, but not tab, ecs, backspace, enter or other keys like those.

Is there any way of doing so?

Edit: btw, I can only use pure Javascript for this project, no libraries like jQuery etc.

Share Improve this question edited Feb 23, 2021 at 14:53 Tobias H. asked Feb 23, 2021 at 14:47 Tobias H.Tobias H. 5052 gold badges7 silver badges22 bronze badges 3
  • stackoverflow./a/18316821/6999390 – Dan Cantir Commented Feb 23, 2021 at 14:49
  • @DanCantir I'm sorry, but I can't use jQuery or any other library for this project. – Tobias H. Commented Feb 23, 2021 at 14:52
  • keypress is deprecated. – D. Pardal Commented Jul 12, 2021 at 17:33
Add a ment  | 

5 Answers 5

Reset to default 2

The ment on your question, gives you jQuery solution that will not work.

You need to do it this way with vanilla JS. keyCode is property on event object, that stores the pressed keyboard button.

Here, you have all keycodes that you can use https://css-tricks./snippets/javascript/javascript-keycodes/

document.onkeydown = (e) => {
    if(e.keyCode === 9) {
      console.log(e);
    }
}

Try this

document.addEventListener("keydown", function(event) {
  console.log(event.which);
})

https://css-tricks./snippets/javascript/javascript-keycodes/

You can use keydown instead.

document.onkeydown = function(e){
  document.body.textContent = e.keyCode;
  if(e.keyCode === 9){
     document.body.textContent += ' Tab pressed';
  }
}

I took a couple of things from the different answers on my post, and I got it to work.

document.onkeydown = (e) => {
    if(e.key === 'Tab') {
        console.log(e.key);
    }
}

Tabkey is an event code. You can catch that event and use e.keyCode ===9 to get the Tab. I think it will still go to the next element in the tabIndex so you will need to preventDefault as well.

发布评论

评论列表(0)

  1. 暂无评论