skip to Main Content

Here I am going through an array of buttons and on each one I create an EventListener. In these EventListeners I’m creating an anonymous fonction that takes a parameter evt.

I don’t understand how JavaScript allows me to use x.target to refer to the button being clicked.

export function ajoutListenersAvis() {
  const piecesElements = document.querySelectorAll(".fiches article button");
  for (let i = 0; i < piecesElements.length; i++) {
    piecesElements[i].addEventListener("click", function(x) {
      const id = x.target.dataset.id;
      fetch(`http://localhost:8081/pieces/${id}/avis`);
    });
  }
}

2

Answers


  1. In the context of your code, x is actually an event object that represents the event being fired when a button is clicked. In this case, it is the click event.

    When you define an event listener with addEventListener, the function you pass as the second argument is automatically passed an event object as its first parameter. This is why you are able to reference x in your anonymous function.

    x.target in your code refers to the button element that was clicked, because target is a property of the event object that points to the DOM element on which the event was triggered. Since you are attaching the event listener to a button element, x.target will always refer to the button element that was clicked.

    Login or Signup to reply.
  2. Although people have answered it in a technical manner, here is a visual representation in a most basic format.

    You can refer to the arguments passed to a function however you would like. It doesn’t change the content in the argument, just how you refer to it.

    const taco = "Pizza";
    
    function test(cheese){
      console.log(cheese)
    }
    
    test(taco)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search