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:
- execute
foo()
- inside said function,
window.addEventListener("scroll", bar());
- then, and only then, have
bar()
be executed upon every single scroll (until I decide toremoveEventListener()
somewhere else).
What happens: bar()
only gets executed once - during the life span of foo()
, I suppose.
A workaround is to
- add the event listener outside of the function (globally),
- encapsulate the code in
bar()
insideif (some_boolean === true) {
, - set my
some_boolean
variable (declared globally) to true beforefoo()
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:
- execute
foo()
- inside said function,
window.addEventListener("scroll", bar());
- then, and only then, have
bar()
be executed upon every single scroll (until I decide toremoveEventListener()
somewhere else).
What happens: bar()
only gets executed once - during the life span of foo()
, I suppose.
A workaround is to
- add the event listener outside of the function (globally),
- encapsulate the code in
bar()
insideif (some_boolean === true) {
, - set my
some_boolean
variable (declared globally) to true beforefoo()
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 whenscroll
takes place.. – Rayon Commented Mar 14, 2016 at 4:58
1 Answer
Reset to default 4bar()
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
版权声明:本文标题:javascript - Execute addEventListener() inside a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744082828a2587967.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论