Keydown Event Listener and Focus
Gianni Castellano
Posted on May 30, 2024
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>
JavaScript
const easterEggImage = document.getElementById('easterEgg')
easterEggImage.addEventListener("keydown", handleKeyDown);
function handleKeyDown(event) {
if (event.key.toLowerCase() === "h") {
easterEggImage.style.display = "block";
}
}
CSS
#easterEgg {
display: none;
position: fixed;
left: 0;
bottom: 0px;
margin-left: 5%;
max-width: 90%;
}
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);
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.
Posted on May 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024