🎉 Making Things Happen with Event Handling in JavaScript 🎉
Events are an essential part of making web pages interactive and responsive. In JavaScript, we can assign event handler functions to elements to make them react to user inputs like clicks, hovers, key presses, and more.
Let’s look at some examples of handling everyday events in JavaScript using addEventListener:
👆 Responding to Clicks
We can run a function when an element is clicked by using addEventListener:
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
Now when the button with the id “myButton” is clicked, the alert pops up. Easy!
👀 Reacting to Hover
To run code when the user hovers over an element, we can use addEventListener:
const img = document.getElementById('photo');
img.addEventListener('mouseover', function() {
img.style.border = "5px solid red";
})
Here we change the image's border with id “photo” when hovered over.
⌨️ Detecting Key Presses
The onkeydown
event handler checks for key presses:
document.addEventListener('keydown', function(event) {
if(event.keyCode == 13) {
submitForm();
}
});
When the Enter key is pressed (key code 13), we call a submitForm()
function.
🎊 Putting It All Together
With just a bit of JavaScript, we can make our pages dynamic and interactive! Event listeners let our code spring into action when users click, hover, type, and more.
Here’s a recap of some useful events we can listen for:
click
- when an element is clickedmouseover
/mouseout
- on mouse hoverkeydown
- when keys are pressedload
- when the page finishes loading
The possibilities are endless! Go forth and create some eventful web apps!
👏 Did you find this post helpful?
If you enjoyed this article, please show your appreciation by clapping below 👏 — it means a lot to me!
Also, don’t forget to follow me on Medium using the link below to stay up to date with my latest JavaScript articles.
❤️ Click the clap button below to show your support!
👉 Follow me on Medium to get my latest JavaScript tutorials.
Thanks for reading! Now you’re ready to start building interactive web pages by handling events in JavaScript.