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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742333315a4424152.html
评论列表(0条)