Categories
interview

Understanding the Difference Between event.target and event.currentTarget in JavaScript

In JavaScript, when handling an event in the browser, there are two different ways to access the event target: event.currentTarget and event.target.

event.target refers to the element on which the event was originally triggered. This may be the element that was clicked on or interacted with by the user.

event.currentTarget refers to the element that the event listener is attached to. This may be the parent element or some other ancestor of the element that was clicked on.

Here’s an example to illustrate the difference between event.target and event.currentTarget:

<body>
  <div class="parent">
    <button class="child">Click me</button>
  </div>
</body>

<script>
  const parent = document.querySelector('.parent');
  const child = document.querySelector('.child');

  parent.addEventListener('click', function(event) {
    console.log(`Current target: ${event.currentTarget.tagName}`);
    console.log(`Target: ${event.target.tagName}`);
  });

  child.addEventListener('click', function(event) {
    console.log(`Current target: ${event.currentTarget.tagName}`);
    console.log(`Target: ${event.target.tagName}`);
  });
</script>

In this example, we have a parent element with a child element inside it. We attach a click event listener to both the parent and child elements.

When we click on the child element, the event listener attached to the child element is triggered first. In this case, the current target and target are both the child element.

Next, the event listener attached to the parent element is triggered because the click event bubbles up from the child element to its parent. In this case, the current target is the parent element (because that’s where the event listener is attached), but the target is still the child element (because that’s where the click event originated).

So, in summary, event.currentTarget refers to the element that the event listener is attached to, while event.target refers to the element on which the event was originally triggered.