I want to add an HTML class to an element as long as the Alt modifier is pressed. The following observations were made using a current version of Google Chrome (same behavior in Opera).
const rootElement = document.querySelector(':root')
document.addEventListener('keydown', function(event) {
if (event.altKey) {
rootElement.classList.add('modifier-pressed')
}
})
document.addEventListener('keyup', function(event) {
// This should be `event.altKey`, but it’s never `true`.
// Checking for the actual key code works ¯\_(ツ)_/¯:
// if (event.keyCode === 18) {
if (event.altKey) {
rootElement.classList.remove('modifier-pressed')
}
})
The first part works fine. Listening for the keydown
event allows me to add the class when the key is pressed.
The second part does not work. Even though the Alt key is down at the moment the keyup
event is fired, the event.altKey
property is set to false
. This is contradictionary to the reported event.keyCode
: 18 (the Alt key). Atleast the way I understand it.
The Mozilla Developer Network page for the event lists the property event.altKey
as expected: It should be true
when it the key was down when firing.
So this is pretty unexpected as far as I’m concerned. However it gets worse: In Firefox, on both events (keydown
and keyup
), the property event.altKey
is set to false
while the key code is as expected (18).
How to riddle this? Did I understand it right and this behavior is indeed unexpected or is my understanding wrong? What is going on?
According to w3c docs altKey event attribute returns true if it's press and false if not, so your code is working right. On keydown event alt is pressed - so it returns keycode 18 and true , on keyup alt is not pressed, so the result is 18 and false.
Check link - https://www.w3.org/TR/uievents/#dom-keyboardevent-altkey
KeyboardEvent.altKey : true if Alt modifier was active, otherwise false