DEV Community

Cover image for Event Delegation
_Khojiakbar_
_Khojiakbar_

Posted on

1

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!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay