Quicktip, know your targets

Ran Wahle
Israeli Tech Radar
Published in
1 min readNov 24, 2019
Javascript — The queen of programming languages

Look at this piece for HTML:

<button class="edit-button"> <i class="fas fa-pencil-alt"></i></button>

as you can see, it has a button that contains an ‘i’ element, with a fontawesome icon inside, which means that our button contains another element inside it.

Now, try to have a click event listener added to that button.

const editButtonClick = (evt) => {

const button1 = evt.target;
const button2 = evt.currentTarget;

//button1 - the nearest element the one that actually triggred the event, which is the 'i' element
//button2 - the button that the event handler has been added to

}
this.querySelector('.edit-button').onclick = editButtonClick;

As it says in the comment, evt.target is the element that triggered the event, while the evt.currentTarget is the element that the event listener has been attached to.

Let’s wrap

Because the event is bubbled, you may attach the event listener to a higher level element and its event handler will run, however, its target will remain the element that triggered the event, and if we want to relate to the one that we’ve added a listener to, we will use the currnetTarget member.

--

--