简体   繁体   中英

Detect when the Tab-Key is pressed using Javascript

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.

Try this

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

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

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 usehttps://css-tricks.com/snippets/javascript/javascript-keycodes/

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

You can use keydown instead.

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

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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM