admin管理员组

文章数量:1393920

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?

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?

Share Improve this question edited Oct 23, 2019 at 18:23 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 14, 2016 at 4:54 Samuel LOL HacksonSamuel LOL Hackson 1,2212 gold badges8 silver badges12 bronze badges 1
  • Use window.addEventListener("scroll", bar);...Remove ()..It will invoke the handler initially not when scroll takes place.. – Rayon Commented Mar 14, 2016 at 4:58
Add a ment  | 

1 Answer 1

Reset to default 4

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);

本文标签: javascriptExecute addEventListener() inside a functionStack Overflow