What is the exact difference between currentTarget property and target property in javascript
Basically, 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.
See a simple explanation on this blog post.
target
= element that triggered event.
currentTarget
= element that has the event listener.
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 event1
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.