7

I have the following jQuery function which triggers aTestEvent() when the user scrolls horizontally past 500 pixels:

jQuery(document).scroll(function(){
    if(jQuery(this).scrollLeft() >= 500){
           aTestEvent();
 }});

Here's the issue: I only want aTestEvent() to be triggered once! However, every time the user scrolls back to the beginning of the page and then again past 500 pixels, aTestEvent() is triggered again.

How can we adjust the above code so that the trigger only occurs for the first time the user scrolls past 500 pixels?

1 Answer 1

16

You can use on and off methods:

$(document).on('scroll', function() {
    if( $(this).scrollLeft() >= 500 ) {
        $(document).off('scroll');
        aTestEvent();
    }
});

http://jsfiddle.net/3kacd/

Please Note: This code snippet could "off" all the scroll event available on a particular page but to scroll off only intended scroll handler without disturbing other scroll handlers, we can use a namespace. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match.

$(document).on('name1.scroll', function() {
    if( $(this).scrollLeft() >= 500 ) {
        $(document).off('name1.scroll');
        aTestEvent();
    }
});

http://jsfiddle.net/shekhardtu/3kacd/57/

Sign up to request clarification or add additional context in comments.

8 Comments

That does the trick! Thank you very much. Will accept once I can.
Another handy trick is the lesser-known .one() method. api.jquery.com/one Very useful every once in a while, but it wouldn't technically work for this because of the if() statement - it would only fire once, even if the if condition was false.
@undefined why did you put .off before the event?
@raam86 off unbinds the handler registered by on method, as OP wants to stop listening to the event I have used off.
of course. but why not: console.log('aTestEvent'); $(document).off('scroll'); So it turns off after the event is fired. This is genuine intrigue
|

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.