Build 15 JS projects YT tutorial

Hello all :slight_smile:

Hope everyone is well and enjoying good weather.

I have a question relating to the youtube video on 15 JS projects on the FCC channel

This is the code sample in question

btns.forEach(function (btn) {
   btn.addEventListener("click", function (e) {
    const question = e.currentTarget.parentElement.parentElement;

    question.classList.toggle("show-text");
  });
});

The following code comes up in an example for creating an interactive FAQ/Questions section, and I could follow along for the most part, but one of the things I didn’t follow was the purpose of the argument “e”. what does the “e” represent? what is it pointing towards? Is it acting like this when paired with .currentTarget ?

Thanks for taking the time to read this far :slight_smile:

Cheers,

Don

e is the conventional way of declaring “event”, here specifically meaning a click event attached to the buttons. e.currentTarget points towards the element that the event listener has been attached to.
Here’s some reading on Event.currentTarget at MDN

1 Like

.currentTarget and this should be the same as long as the callback is a normal function and not an arrow function.

<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
document.querySelectorAll(".btn").forEach((btn) => {
  btn.addEventListener("click", function (event) {
    console.log(event.currentTarget); // the button clicked
    console.log(this); // the button clicked
  });
});
document.querySelectorAll(".btn").forEach((btn) => {
  btn.addEventListener("click", (event) => {
    console.log(event.currentTarget); // the button clicked
    console.log(this); // Window
  });
});
1 Like

Wow, thank you for clarifying this for me :slight_smile:

Is there a reason between normal and arrow functions?

Thank you for the link! Documentation is one of the best things about learning to code, so many resources.

Arrow functions has what’s known as lexical this.

MDN: Arrow function expressions

Arrow functions establish “this” based on the scope the Arrow function is defined within.

JavaScript for impatient programmers: Callable values

…the arrow function does not have its own this. this is resolved lexically, just like any other variable. That’s why the this of arrow functions is called lexical.

1 Like

Thank you @lasjorg :slight_smile:

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