Sobes.tech
Middle+

Using only the DOM API (without React, through document), write code that outputs the color of a rectangle when clicked. It is preferable to use a single event handler for all elements. What is the difference between event.target and event.currentTarget?

sobes.tech AI

Answer from AI

To handle clicks on multiple rectangles with a single event handler, you can use event delegation — attach the handler to a common container and determine which element was clicked.

Example code:

<div id="container">
  <div class="rect" style="width:100px; height:50px; background-color:red;"></div>
  <div class="rect" style="width:100px; height:50px; background-color:green;"></div>
  <div class="rect" style="width:100px; height:50px; background-color:blue;"></div>
</div>

<script>
  const container = document.getElementById('container');

  container.addEventListener('click', function(event) {
    // event.target — the element on which the click occurred
    // Check if the click was on a rectangle
    if (event.target.classList.contains('rect')) {
      const color = getComputedStyle(event.target).backgroundColor;
      alert('Rectangle color: ' + color);
    }
  });
</script>

Difference between event.target and event.currentTarget:

  • event.target — the element where the event originally occurred (for example, the element that was clicked).
  • event.currentTarget — the element on which the event handler is currently executing (in our case — the container #container).

In event delegation, the handler is attached to the parent (currentTarget), and target points to the specific child element that triggered the event.

Using only the DOM API (without React, through… - sobes.tech