Event Listeners in JavaScript: Cleaner Code with JavaScript

#DAY 17 — Listening Better: Event Listeners in JavaScript** We’re leveling up today 🔥 Yesterday, we used `onclick` directly inside HTML. Today, we learn a cleaner and more powerful way: 👉 Event Listeners 💡 What Is an Event Listener? An lkķevent listener is JavaScript telling your website: > “Hey, watch this element… when something happens, do this.” It separates your HTML from your JavaScript — making your code cleaner and more professional 💻✨ 🧠 Real-Life Example Think of it like assigning a security guard 🛡️ * “Stand here (element)” * “If someone enters (event)” * “Do this (action)” That’s exactly what event listeners do. 🧪 Example Code ```html <!DOCTYPE html> <html> <head> <title>Day 17</title> </head> <body> <h1 id="text">Welcome 👋</h1> <button id="btn">Click Me</button> <script> const button = document.getElementById("btn"); button.addEventListener("click", function() { document.getElementById("text").innerHTML = "You used an event listener! 🎉"; }); </script> </body> </html> ``` 🔍 What’s Happening? * `getElementById` → selects the button * `addEventListener("click", function)` → listens for clicks * When clicked → runs the function and updates the text ⚡ Why This Is Better Than `onclick` * Cleaner structure 🧹 * Easier to manage large projects * You can add multiple events to one element 🎯 Mini Challenge Try this: * Add a second button that changes text color 🎨 * Or make a button that hides text completely 🏁 Progress Check At this point, you can: * Structure a webpage (HTML) ✅ * Style it beautifully (CSS) ✅ * Add interactivity (JavaScript) ✅ You’re no longer a beginner… You’re becoming a frontend developer in motion 🚀 🔥 What’s Next? Tomorrow, we’ll start working with user input (forms) — where real applications begin 👀 #30DaysOfCode #JavaScript #WebDevelopment #Frontend #BuildInPublic #TechJourney

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories