Event Delegation

__khojiakbar__

_Khojiakbar_

Posted on July 2, 2024

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!

πŸ’– πŸ’ͺ πŸ™… 🚩
__khojiakbar__
_Khojiakbar_

Posted on July 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Mastering JavaScript Event Delegation
javascript Mastering JavaScript Event Delegation

November 23, 2024

Understanding JavaScript Event Delegation
javascript Understanding JavaScript Event Delegation

September 1, 2024

Event Delegation
event Event Delegation

July 2, 2024

Mastering JavaScript Event Delegation
javascript Mastering JavaScript Event Delegation

June 10, 2024

Event Delegation - JavaScript
undefined Event Delegation - JavaScript

March 17, 2024