0

I'm still quite new to coding so sorry if this is a question with an obvious answer.

I'm using event listeners in JavaScript to toggle the display of a paragraph on a webpage. I can get it to work but am confused as to why certain syntax isn't valid.

If I type moreInfoButtonCourse1.addEventListener("click", toggleDisplay(course1Info)); then nothing happens; the function doesn't work. However if I change this to

moreInfoButtonCourse1.addEventListener("click", () => {
  toggleDisplay(course1Info);
});

then it does work. Why is the first option invalid but the second is fine? Thanks!

  • 2
    The first is incorrect because `toggleDisplay(course1Info)` calls the function immediately and gives the result to `addEventListener`. It expects a function, rather than the function's result. – General Grievance Jul 27 '23 at 22:38

1 Answers1

0

The issue is that in your first example you're invoking the function as it is added:

moreInfoButtonCourse1.addEventListener("click", toggleDisplay(course1Info));

toggleDisplay(courseInfo) gets called as soon as you add the event listener, and it presumably returns undefined, which is what is getting added as a function - and so no function is called when the event is trigger.

Your other example is doing the correct thing - it's adding a function which calls toggleDisplay(courseInfo).

Cody
  • 36
  • 3