event.target vs event.currentTarget
You'll learn the crucial difference between the element that actually triggered an event and the element your listener is attached to.
The Core Distinction
When you attach an event listener to an element, two important references are available in the event object:
event.target- The specific element that was actually clicked, typed on, or otherwise interacted with (the "origin" of the event)event.currentTarget- The element that your event listener is attached to (where you calledaddEventListener)
These are often the same element, but during event bubbling, they can be different.
Why This Matters
Imagine you have a button inside a card, and you attach a click listener to the card. When someone clicks the button:
event.targetrefers to the button (what they actually clicked)event.currentTargetrefers to the card (where your listener lives)
Think of it like mail delivery: event.target is the person who sent the letter, while event.currentTarget is your mailbox where you're checking for mail.
Practical Example
const card = document.querySelector('.card');
card.addEventListener('click', function(event) {
console.log('Clicked element:', event.target);
console.log('Listener attached to:', event.currentTarget);
// event.currentTarget always equals 'this' in traditional functions
});
If the card contains multiple child elements (headings, paragraphs, buttons), event.target will be whichever one was clicked, but event.currentTarget will always be the card itself.
Key Takeaway: Use event.target to find out what was actually clicked, and event.currentTarget to reference the element where your listener is attached—they're often different during event bubbling.