DEV Community

Gianni Castellano
Gianni Castellano

Posted on

1

Keydown Event Listener and Focus

Hello readers! Welcome to my first blog where I will be discussing the issues and resolution I had with the "Keydown" event listener in JavaScript. When trying to implement my last event listener I struggled for an hour trying to understand why it was not working although the logic was all there. Here is the original HTML, JavaScript, and CSS for my code:
HTML

<img src="https://pbs.twimg.com/profile_images/1364220282790109188/uT0fQV56_400x400.jpg" alt="blue party hat" id="easterEgg" tabindex="0">
    <div>
Enter fullscreen mode Exit fullscreen mode

JavaScript

const easterEggImage = document.getElementById('easterEgg') 

easterEggImage.addEventListener("keydown", handleKeyDown);

function handleKeyDown(event) {
  if (event.key.toLowerCase() === "h") {
    easterEggImage.style.display = "block";
  }
}
Enter fullscreen mode Exit fullscreen mode

CSS

#easterEgg {
    display: none;
    position: fixed;
    left: 0;
    bottom: 0px;
    margin-left: 5%;
    max-width: 90%;
}
Enter fullscreen mode Exit fullscreen mode

The idea of this was to make an image appear whenever the user pressed the "h" key. Unfortunately it was not working and I could not understand why. After doing research I became more familiar with the concepts of "Event Delegation" and "direct event attachment". When I was using the descendant element easterEggImage I was only giving instruction for to apply the event to that element only. This is not what I intended so in order to fix this I attached the addEventListener to the document instead. Here is the working code below:

document.addEventListener("keydown", handleKeyDown);
Enter fullscreen mode Exit fullscreen mode

Now my keydown event will trigger anywhere in the document! So after my hour long struggle I was able to get my image to appear with this function.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (1)

Collapse
 
softwaredeveloping profile image
FrontEndWebDeveloping

Thanks for telling us @gianni_cast ! We like to hear about people learning journeys, and we need more people writing posts to help other beginners. Thank you! If you would like to hang out with other devs feel free to join our new community one Discord.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay