When to use .target?

I’m doing the DOM events with javascript project.

In this image, how comes the function keyPlay needs to use target to access the element, whereas the function changeKeyColor can directly use the note?

I.e. why is .target used over say just referencing a parameter that equals the note you want to click?

If you think about it, when you write note.onmousedown = KeyPlay; that does use the target to access the element because it calls KeyPlay and KeyPlay uses target.

thanks! so say i have a normal event and handler. how comes you don’t always use target? I don’t quite get what target does and I think i made an error. It should be:

let keyPlay = event => {
event.target.style.backgroundColor = ‘ble’;

if event is mentioned above (so we know its referring to event) why is .target needed?

The target property of an event object is a reference to the node of origin of said event.
It can be used to ensure that you’re not randomly targeting something that propagates up from a node (read about propagation in the MDN docs for more on that).

You can also do things like aim for multiple targets

   document.body.addEventListener("click", event => {
      if (event.target.nodeName == "BUTTON") {
           console.log("This button was clicked", event.target.textContent);

//ouput for clicking button 1: This button was clicked 1
//ouput for clicking button 2: This button was clicked 2
//ouput for clicking button 3: This button was clicked 3
1 Like

I will read up about it - thanks so much man!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.