JavaScript isn’t just about variables, loops, and logic — it’s about bringing your website to life. And that magic begins with events.
Welcome to Day 6 of your JavaScript journey! Today, we dive into one of the most exciting parts of JavaScript: Events.
💡 What Are Events?
An event is anything that happens in the browser — like a user clicking a button, moving the mouse, submitting a form, or pressing a key. JavaScript lets you listen for these events and respond to them.
Think of it like this:
“Hey JavaScript, when the user clicks this button, please do something!”
🛠️ How to Handle Events
JavaScript provides a powerful method to handle events:
addEventListener()
This method allows you to attach a function that runs when an event happens.
🔗 Syntax:
javascript
element.addEventListener("event", function);
🧪 Simple Example – Click Event
html
Copy
Edit
Click Me!
document.getElementById("clickMe").addEventListener("click", function() {
alert("You clicked the button!");
});
💥 When the user clicks the button, an alert pops up. That’s interactivity in action!
🎯 Common Events You Should Know
Event Description
click When an element is clicked
mouseover When mouse hovers over an element
keydown When a key is pressed
submit When a form is submitted
change When an input value changes
🧠 Understanding the Event Object
Every event handler receives an event object with useful information.
javascript
Copy
Edit
document.addEventListener("keydown", function(event) {
console.log("You pressed: " + event.key);
});
You can use properties like:
event.key → which key was pressed
event.target → which element triggered the event
event.preventDefault() → stops default browser behavior
🛑 Preventing Default Actions
Imagine you don’t want a form to reload the page on submit:
javascript
Copy
Edit
const form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Stops the form from reloading the page
console.log("Form submitted!");
});
🌟 Final Thoughts
Events are the heartbeat of web interactivity. With them, your static webpage turns into a dynamic experience. On Day 6, mastering events will set the foundation for things like form validation, interactive UI components, and even full web apps.
You're not just writing code anymore — you're giving your website superpowers. 🦸♂️🦸♀️