Navspace
Navspace

Reputation: 101

detect up/down and tab keys press in JavaScript

How can I detect if the up/down/left/right or the tab key is pressed, I tried to use the code below but it doesn't print something when those keys are pressed

document.addEventListener('keypress', (e) => {
    console.log(e.key)
})

Upvotes: 1

Views: 27

Answers (2)

Rahul Mohanty
Rahul Mohanty

Reputation: 342

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38') {
        console.log("up arrow")// up arrow
    }
    else if (e.keyCode == '40') {
        console.log("down arrow")// down arrow
    }
    else if (e.keyCode == '9') {
       console.log("tab")// tab
    }
 

}

Upvotes: 0

flyingfox
flyingfox

Reputation: 13506

You need to use keydown instead of keypress

document.addEventListener("DOMContentLoaded", function(event) {
   document.addEventListener('keydown', (e) => {
    console.log(e.keyCode)
   })
})

Upvotes: 2

Related Questions