1

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.

Tobias H.
  • 426
  • 1
  • 6
  • 18

5 Answers5

2

The comment 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.com/snippets/javascript/javascript-keycodes/

document.onkeydown = (e) => {
    if(e.keyCode === 9) {
      console.log(e);
    }
}
Terminat
  • 1,199
  • 5
  • 21
  • 1
    When I type this into my code editor, it puts a line over the text,and says that 'keyCode' is deprecated. And it logged nothing out when I tryed. – Tobias H. Feb 23 '21 at 14:57
  • 4
    One more thing: tab is handled using `keydown`, not `keypress`. – Wais Kamal Feb 23 '21 at 14:59
  • @TobiasH. that's correct. Instead of `e.keyCode`, you can use `e.key`, which takes a string instead of a numerical code (in this case, `"Tab"`.) – Milo Apr 13 '23 at 16:27
1

Try this

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

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

Isaac Bruno
  • 254
  • 1
  • 8
1

You can use keydown instead.

document.onkeydown = function(e){
  document.body.textContent = e.keyCode;
  if(e.keyCode === 9){
     document.body.textContent += ' Tab pressed';
  }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

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.

QT Ray
  • 1,256
  • 8
  • 12
0

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);
    }
}
Community
  • 1
  • 1
Tobias H.
  • 426
  • 1
  • 6
  • 18