I am new to dom manipulation , here I am trying to change the colour of the smallest box using the arrow key. I am able to access the same using the click events.
<body>
<div class="container">
<div class="main-box" id="main-box">
<div class="moving-box" id="moving-box">
</div>
</div>
</div>
<script src="script.js"></script>
</body>
const box = document.getElementById("moving-box");
const mainBox = document.getElementById("main-box");
box.addEventListener("keypress", function (event) {
if (event.keyCode === 38) {
box.style.backgroundColor = red;
}
})
2
Answers
I think the problem is event.keyCode is deprecated, you should try event.key (ArrowRight, ArrowLeft, ArrowUp, ArrowDown)
Further info: https://www.w3schools.com/jsref/event_key_key.asp
There’s no
keypress
event for the keyboard arrows becausehttps://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event
So we should probably use
keydown
, also you aren’t clear whether you want to execute the event handler with the box focused or not. If focused you needtabindex="0"
so the box could receive focus. Otherwise add the event listener todocument.body
.Also note that the keyboard keys scroll the page. So you should call
event.preventDefault()
to halt that.