Funny Example
Alright, let's use a funny example with a classroom and students. Imagine a classroom full of students, and each student is holding a card. When you tap a student's card, they say something funny. Instead of going to each student and asking them to say something funny when tapped, you tell the teacher to watch over all the students and handle it.
Here's how it works with event delegation:
- The Students and the Teacher:
- The students are the items you want to interact with.
- The teacher is the parent element that listens for the tap (click) on any student's card.
- The Plan:
- You tell the teacher, "Hey, whenever someone taps a student's card, let's make that student say something funny!"
Now, let's see this in JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Event Delegation Classroom</title>
</head>
<body>
<div id="classroom">
<div class="student" style="background-color: yellow;">🧑‍🎓</div>
<div class="student" style="background-color: orange;">🧑‍🎓</div>
<div class="student" style="background-color: pink;">🧑‍🎓</div>
</div>
<script>
// The teacher (parent)
const classroom = document.getElementById('classroom');
// Add an event listener to the teacher
classroom.addEventListener('click', function(event) {
// Check if the clicked element is a student
if (event.target.classList.contains('student')) {
alert('Student says: "Why was the math book sad? It had too many problems!"');
}
});
</script>
</body>
</html>
So, event delegation is like having a teacher who handles all the funny jokes for the students, making it easier and more efficient!
Top comments (0)