I want to create a web page that would enable a user to light up the boxes/items on the page using a specified key on the keyboard. For example, below, using ‘M’ to light up the middle item on the interface - Or ‘F’ to light up the top item. I would like the functionality to be able light up multiple boxes at the same time whilst pressing multiple buttons.

I've been advised to use event decorators, but I'm not entirely sure where to start.

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 37) {
        alert('Left was pressed');
    else if(event.keyCode == 39) {
        alert('Right was pressed');

1 Answers

Jack Bashford On

Just check for specific letter keys, and perform actions based on those:

document.addEventListener("keydown", ({ keyCode }) => {
  if (document.getElementById(keyCode)) document.getElementById(keyCode).classList.add("active");
document.addEventListener("keyup", () => {
  document.querySelectorAll(".key").forEach(elem => elem.classList.remove("active"));
.active {
  background-color: gold;
<div id="77" class="key">M</div>
<div id="70" class="key">F</div>
<div id="76" class="key">L</div>