3

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..

3
  • Does it work? Looks fine to me really Commented May 6, 2015 at 17:25
  • possible duplicate of jQuery scroll() detect when user stops scrolling Commented May 6, 2015 at 17:30
  • 1
    @Jako not dublicate. I'm trying to find out how " to activate an on scroll listener after a click event" as posted. Not detect when user stops scrolling. Totally different! Commented May 6, 2015 at 17:32

3 Answers 3

6

You could use jQuery .one():

$('.button').on('click', function() {
    $(window).one('scroll', someFunction);
});
Sign up to request clarification or add additional context in comments.

Comments

3

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
}

1 Comment

Thanks! This is why I was having trouble! I would vote as correct answer but Sergey's solution $(window).one('scroll', someFunction); seems to work as well with less code.
-1

You can do it the following way:

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

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

6 Comments

is there a difference using bind instead of on?
yea, bind is deprecated
I don't find any deprecated flags in the api for bind/unbind.
I think, @sal-niro means live.
@Tyr okay you are perhaps correct about official deprecated-ness, but the docs do state "As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document". Anyways, bind() really shouldn't be used in place of on(). Unless you can think of a good reason?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.