Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on scroll listener after click event

What is the proper way to activate an on scroll listener after a click event?

I'm currently using:

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

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

On a click event I enable the scroll listener which runs someFunction. The function does stuff and disables the scroll listener when finished. The scroll listener is enabled again on click.

My concern is that I'm not doing it right. Please advise!

Note: The scroll listener cannot run indefinitely. It starts on click and must finish at the end of myFunction.

Note: I'm not trying to detect when user stops scrolling..

like image 922
CyberJunkie Avatar asked Jan 18 '26 02:01

CyberJunkie


2 Answers

You could use jQuery .one():

$('.button').on('click', function() {
    $(window).one('scroll', someFunction);
});
like image 87
sergdenisov Avatar answered Jan 19 '26 16:01

sergdenisov


Every single click adds an additional scroll event listener. I would encapsulate the binding with an additional variable:

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
}
like image 26
Alexander Bondar Avatar answered Jan 19 '26 14:01

Alexander Bondar



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!