JQuery to listen to scroll after click event
What is the correct way to activate the scroll listener after a click event?
I am currently using:
$('.button').click(function (event) {
$(window).on("scroll", someFunction);
}
someFunction = function() {
//do stuff
$(window).off("scroll"); //disable scroll listener
}
On the click event, I include a scroll listener that triggers someFunction. The function does things and disables the scroll listener on completion. The scroll listener is reactivated when pressed.
My concern is that I am not doing it right. Please advise!
Note: The scroll listener cannot run indefinitely. It starts with a click and must end at the end of myFunction.
Note. I am not trying to detect when the user stops scrolling.
+3
source to share
3 answers
Each click adds an additional scroll event listener. I would encapsulate an additional variable binding:
var isScrollBindingActive = false;
$('.button').click(function (event) {
if (!isScrollBindingActive) {
isScrollBindingActive = true;
$(window).on("scroll", someFunction);
}
}
someFunction = function() {
//do stuff
$(window).off("scroll"); //disable scroll listener
isScrollBindingActive = false; // allow binding again if wished
}
+3
source to share