What is the exact difference between currentTarget property and target property in JavaScript

Javascript

Javascript Problem Overview


Can anyone please tell me the exact difference between currentTarget and target property in JavaScript events with example and which property is used in which scenario?

Javascript Solutions


Solution 1 - Javascript

Events bubble by default. So the difference between the two is:

  • target is the element that triggered the event (e.g., the user clicked on)

  • currentTarget is the element that the event listener is attached to.

Solution 2 - Javascript

target = element that triggered event.

currentTarget = element that has the event listener.

Solution 3 - Javascript

Minimal runnable example

window.onload = function() {
  var resultElem = document.getElementById('result')
  document.getElementById('1').addEventListener(
    'click',
    function(event) {
      resultElem.innerHTML += ('<div>target: ' + event.target.id + '</div>')
      resultElem.innerHTML += ('<div>currentTarget: ' + event.currentTarget.id + '</div>')
    },
    false
  )
  document.getElementById('2').dispatchEvent(
          new Event('click', { bubbles:true }))
}

<div id="1">1 click me
  <div id="2">2 click me as well</div>
</div>
<div id="result">
  <div>result:</div>
</div>

If you click on:

2 click me as well

then 1 listens to it, and appends to the result:

target: 2
currentTarget: 1

because in that case:

  • 2 is the element that originated the event
  • 1 is the element that listened to the event

If you click on:

1 click me

instead, the result is:

target: 1
currentTarget: 1

Tested on Chromium 71.

Solution 4 - Javascript

If this isn't sticking, try this:

current in currentTarget refers to the present. It's the most recent target that caught the event that bubbled up from elsewhere.

Solution 5 - Javascript

For events whose bubbles is true, they bubble.

Most events do bubble, except several, namely focus, blur, mouseenter, mouseleave, ...

If an event evt bubbles, the evt.currentTarget is changed to the current target in its bubbling path, while the evt.target keeps the same value as the original target which triggered the event.

Event's target types

It is worth noting that if your event handler (of an event that bubbles) is asynchronous and the handler uses evt.currentTarget. currentTarget should be cached locally because the event object is reused in the bubbling chain (codepen).

const clickHandler = evt => {
  const {currentTarget} = evt // cache property locally
  setTimeout(() => {
    console.log('evt.currentTarget changed', evt.currentTarget !== currentTarget)
  }, 3000)
}

If you use React, from v17, react drops the Event Pooling.

Therefore, the event object is refreshed in the handler and can be safe to use in asynchronous calls (codepen).

↑is not always true. onClick event's currentTarget is undefined after the event handler finishes. In conclusion, always cache the event's properties locally if you are going to use them after a synchronous call.

From react docs

> Note: > > As of v17, e.persist() doesn’t do anything because the SyntheticEvent > is no longer pooled.

And many other things that are too long to be pasted in an answer, so I summarized and made a blog post here.

Solution 6 - Javascript

<style>
  body * {
    margin: 10px;
    border: 1px solid blue;
  }
</style>

<form onclick="alert('form')">FORM
  <div onclick="alert('div')">DIV
    <p onclick="alert('p')">P</p>
  </div>
</form>

If click on the P tag in above code then you will get three alert,and if you click on the div tag you will get two alert and a single alert on clicking the form tag. And now see the following code,

<style>
  body * {
    margin: 10px;
    border: 1px solid blue;
  }
</style>
<script>
function fun(event){
  alert(event.target+" "+event.currentTarget);
}

</script>

<form>FORM
  <div onclick="fun(event)">DIV
    <p>P</p>
  </div>
</form>

We just removed onclick from the P and form tag and now when we click we on P tag we get only one alert:

> [object HTMLParagraphElement] [object HTMLDivElement]

Here event.target is [object HTMLParagraphElement],and event.curentTarget is [object HTMLDivElement]: So

> event.target is the node from which the event originated, and > event.currentTarget, on the opposite, refers to the node on which current-event listener was attached.To know more see bubbling

Here we clicked on P tag but we don't have listener on P but on its parent element div.

Solution 7 - Javascript

> Event.currentTarget is the element to which the event handler has been > attached, as opposed to Event.target, which identifies the element on > which the event occurred and which may be its descendant.

Source: MDN

target always refers to the element in front of addEventListener - it's the element on which the event originated. currentTarget tells you - if this is an event that's bubbling - the element that currently has the event listener attached (which will fire the event handler if the event occurs).

See this CodePen for an example. If you open up developer tools and click the square, you'll see that first the div is the target and the currentTarget, but the event bubbles up to the main element - then main element becomes the currentTarget, while the div is still the target. Note the event listener needs to be attached to both elements for the bubbling to occur.

Solution 8 - Javascript

event.target is the node from which the event originated, ie. wherever you place your event listener (on paragraph or span), event.target refers to node (where user clicked).

event.currentTarget, on the opposite, refers to the node on which current-event listener was attached. Ie. if we attached our event listener on paragraph node, then event.currentTarget refers to paragraph while event.target still refers to span. Note: that if we also have an event listener on body, then for this event-listener, event.currentTarget refers to body (ie. event provided as input to event-listerners is updated each time event is bubbling one node up).

Solution 9 - Javascript

Here's a simple scenario to explain why it's needed. Let's say there are some messages that you show to the user with the format below, but you also want to give them the freedom to close them (unless you have a special mental disorder), so here are some message panes:

[ A message will be in this pane [x] ]

[ A message will be in this pane [x] ]

[ A message will be in this pane [x] ]

and when the user clicks on the [x] button on each, the whole corresponding pane must be removed.

Here's the HTML code for the pane:

<div class="pane">
  A message will be here
  <span class="remove-button">[x]</span>
</div>

Now where do you want to add the click event listener? The user clicks on [x], but you want to remove the pane, so:

  • If you add the click event listener to the [x], then you will have to find its parent on DOM and remove it... which is possible but ugly and "DOM dependent".

  • And if you add the click event listener to the pane, clicking "everywhere on the pane" will remove it, and not just clicking on its [x] button.

So what can we do? We can use the "Bubbles Up" feature of the event system:

> "Events are raised and bubble up the DOM tree regardless of the existence of any event handlers."

In our example, this means that even if we add the event handlers to the panes, we will be able to catch the events raised specifically by the [x] button clicks (because events bubble up). So there can be difference between where an event is raised, and where we catch and handle it.

Where it's raised will be in the event.target, and where it's caught will be in the event.currentTarget (where we're currently handling it). So:

let panes = document.getElementsByClassName("pane");
for(let pane of panes){
    pane.addEventListener('click', hndlr);
}
function hndlr(e){
    if(e.target.classList.contains('remove-button')){
        e.currentTarget.remove();
    }
}

(The credit of this example goes to the website JavaScript.info)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionValli69View Question on Stackoverflow
Solution 1 - JavascriptGriffinView Answer on Stackoverflow
Solution 2 - JavascriptmarkmarijnissenView Answer on Stackoverflow
Solution 3 - JavascriptCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 4 - Javascriptuser1164937View Answer on Stackoverflow
Solution 5 - JavascripttransangView Answer on Stackoverflow
Solution 6 - JavascriptSomesh SharmaView Answer on Stackoverflow
Solution 7 - JavascriptnCardotView Answer on Stackoverflow
Solution 8 - JavascriptYogeshBagdawatView Answer on Stackoverflow
Solution 9 - JavascriptaderchoxView Answer on Stackoverflow