Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute addEventListener() inside a function

What I wanted: Add an event listener to window on scroll, but only when a certain function is fired. The way I wanted it to work is:

  1. execute foo()
  2. inside said function, window.addEventListener("scroll", bar());
  3. then, and only then, have bar() be executed upon every single scroll (until I decide to removeEventListener() somewhere else).

What happens: bar() only gets executed once - during the life span of foo(), I suppose.

A workaround is to

  1. add the event listener outside of the function (globally),
  2. encapsulate the code in bar() inside if (some_boolean === true) {,
  3. set my some_boolean variable (declared globally) to true before foo() ends.

That way, I got the scroll functionality I needed, but now bar() and its boolean check gets executed upon every scroll, when there's absolutely no need to.

Question: How do I add the event handler so that it runs bar() efficiently?

like image 725
Samuel LOL Hackson Avatar asked May 30 '26 06:05

Samuel LOL Hackson


1 Answers

bar() appears to be called, not referenced at window.addEventListener("scroll", bar()); . Try referencing bar as handler to call when scroll event occurs

window.addEventListener("scroll", bar);
like image 85
guest271314 Avatar answered Jun 01 '26 21:06

guest271314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!