📄 Day 11 — DOM Events & Event Listeners
Hi Guys Welcome to Day 11 🎯 Today we’ll explore how web pages become interactive — responding to clicks, hovers, and key presses using **events**. Events are the core of user interaction in web applications.
⚙️ 1️⃣ What is an Event?
An event is any user or system action — clicking a button, typing in a field, or loading a page. JavaScript allows us to “listen” for these actions and execute specific code when they occur.
🧩 2️⃣ Event Handlers
<button onclick="sayHello()">Click Me</button>
<script>
function sayHello() {
alert("Hello, Rahul!");
}
</script>
🎧 3️⃣ Event Listeners (Modern Approach)
Instead of inline events, it’s better to attach event listeners using JavaScript:
let btn = document.querySelector("button");
btn.addEventListener("click", function() {
alert("Button clicked!");
});
🔁 4️⃣ Common Event Types
- click — user clicks an element
- mouseover — mouse hovers
- mouseout — mouse leaves
- keydown — key pressed
- submit — form submission
🧮 5️⃣ Example — Dynamic Background Changer
<button id="change">Change Background</button>
<script>
let btn = document.getElementById("change");
btn.addEventListener("click", () => {
document.body.style.background =
"#" + Math.floor(Math.random()*16777215).toString(16);
});
</script>
🧠 6️⃣ Practice Task
- Create a button that changes text color when clicked.
- Add a mouseover event that enlarges a paragraph.
- Use a keydown event to log the pressed key to the console.
🎯 Summary
Now your web pages can respond to user actions dynamically. Tomorrow, we’ll explore **Arrow Functions & ES6 Features**, making your code cleaner and modern.
Comments
Post a Comment