admin管理员组文章数量:1333392
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
5 Answers
Reset to default 2The 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.
本文标签: keypressDetect when the TabKey is pressed using JavascriptStack Overflow
版权声明:本文标题:keypress - Detect when the Tab-Key is pressed using Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742333315a2455127.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论