We often deal with dom events in the development and often use the two objects e.target and e.currentTarget. But many people don't even know the difference between the two. Today, let's talk about the difference between e.target and e.currentTarget.
Bubble & Capture
When you trigger an element's event, the event is passed down from the element's ancestors, and this process is called capture. After reaching this element, it will be propagated to its ancestor elements, and this process is bubbling.
<div id="a"> <div id="b"> <div id="c"> <div id="d">Example</div> </div> </div> </div>
addEventListener
addEventListener is a method for binding events to elements, and it receives the following three parameters.
The first parameter: the name of the event to be bound
The second parameter: the function to execute
The third parameter: false: default, which means binding when bubbling; true: binding when capturing
target & currentTarget
false
We bind events to four div elements, and if the third parameter of addEventListener is not set, then the default setting is false.
const a = document.getElementById('a') const b = document.getElementById('b') const c = document.getElementById('c') const d = document.getElementById('d') a.addEventListener('click', (e) => { const { target, currentTarget } = e console.log('target is ${target.id}') console.log('currentTarget is ${currentTarget.id}') }) b.addEventListener('click', (e) => { const { target, currentTarget } = e console.log('target is ${target.id}') console.log('currentTarget is ${currentTarget.id}') }) c.addEventListener('click', (e) => { const { target, currentTarget } = e console.log('target is ${target.id}') console.log('currentTarget is ${currentTarget.id}') }) d.addEventListener('click', (e) => { const { target, currentTarget } = e console.log('target is ${target.id}') console.log('currentTarget is ${currentTarget.id}') })
Now let's click and see what's output. It can be seen that the trigger is d, and the executed element is the bubbling order.
target is d currentTarget is d target is d currentTarget is c target is d currentTarget is b target is d currentTarget is a
true
We set the third parameter of the four events to true. We can see from the output that d is triggered, and the elements executed are the order of capture.
target is d currentTarget is a target is d currentTarget is b target is d currentTarget is c target is d currentTarget is d
The difference between e.target and e.currentTarget
From the above, we can draw the following conclusions.
e.target: The element that triggered the event
e.currentTarget: the element to which the event is bound