Pass the event to the callback within the event listener that triggered it?

Pass the event to the callback within the event listener that triggered it?
0
#1

Hi…
Not entirely sure what that means or why one would want to do it. But i really need to understand this procedure(if such a thing exist) for a test i’m taking
Javascript genies Help!

0 Likes

#2

Not entirely understanding the question, but a quick overview of how events in JS work:

We have events, like click or mouseover or keyup or focus, that can be applied to elements of your page. So a click handler might go like this:

let myButton = document.querySelector("#my-button");
myButton.addEventListener("click", myButtonClickHandler)

Now, myButtonClickHandler is the callback function that will be used when the button gets a click. And yes, there is a default Event object that is passed to that automatically:

function myButtonClickHandler(eventObj){
  // We can prevent any other default  actions on that button like this:
  eventObj.preventDefault();

  // in the event object, Event.target is the thing that actually got clicked
  let clickedEl = eventObj.target;

  if (clickedEl.value == 'Shoes'){
    console.info("Hey! You clicked SHOES! Nice!");
  }
}

So we have this nifty Event object with information about that event: in a keyup handler, you might use Event.which to determine which key was pressed, for example.

Remember, the MDN (Mozilla Developers) are your friend, and most of the answers to questions like this live there: https://developer.mozilla.org/en-US/docs/Web/API/Event

1 Like

#3

Thanks this has been useful

0 Likes