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


You can use jQuery . one () :



$('.button').on('click', function() {
    $(window).one('scroll', someFunction);
});

      

+6


source


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


You can do it like this:

$('.button').click(function (event) {
   $(window).bind("scroll", someFunction);
}

someFunction = function() {
   //do stuff 
   $(window).unbind("scroll"); // remove scroll listener
}

      

-1


source







All Articles