JS - Passing arguments via event listener (or event handler)

When a function  is used as an event handler, its this is set to the element the event fired from.

 

const CTA = document.querySelector(".cta a");
const ALERT = document.querySelector("#booking-alert");

CTA.classList.remove("hide");
ALERT.classList.add("hide");

function reveal(e, current) {
    e.preventDefault();
    current.innerHTML == "Book Now!" ? current.innerHTML = "oops!" : current.innerHTML = "Book Now!";
    ALERT.classList.toggle("hide");
}

CTA.addEventListener("click", function(e) {
  reveal(e, this);
}, false);
CTA.addEventListener("click", function(){
  console.log("The button was clicked!")
}, false);

Compare with event handler:

When an event like click is fired, we can catch the event object as an attribute in the function that is triggered. The convention here is to give the event object the name e, and now, inside our function, we can refer to the event object, e, and then apply the prevent default method to it,so e.preventDefault.

const CTA = document.querySelector(".cta a");
const ALERT = document.querySelector("#booking-alert");

CTA.classList.remove("hide");
ALERT.classList.add("hide");

function reveal(e) {
    e.preventDefault();
    CTA.classList.toggle("hide");
    ALERT.classList.toggle("hide");
}

CTA.onclick = reveal;

Event objects

Though we have ignored it so far, event handler functions are passed an argument: the event object. This object holds additional information about the event. For example, if we want to know which mouse button was pressed, we can look at the event object’s button property.


The information stored in an event object differs per type of event. We’ll discuss different types later in the chapter. The object’s type property always holds a string identifying the event (such as "click" or "mousedown").

 

ref: https://eloquentjavascript.net/

你可能感兴趣的:(WebDev)