DEV Community

Cover image for Event Delegation
_Khojiakbar_
_Khojiakbar_

Posted on

Event Delegation

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:

  1. 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.
  1. 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>

Enter fullscreen mode Exit fullscreen mode

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)