Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Scroll Function Keeps Triggering: Only Once Please

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?

like image 607
tehSUPERADMIN Avatar asked May 28 '13 01:05

tehSUPERADMIN


People also ask

How to trigger the scroll event manually using JavaScript?

The scroll event handler can be bound to this element: Now when the user scrolls the text up or down, one or more messages are appended to <div id="log"></div>: Handler for .scroll () called. To trigger the event manually, apply .scroll () without an argument: After this code executes, clicks on Trigger the handler will also append the message.

What is the purpose of the scroll () method?

The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.

What is the use of trigger () function?

A function to execute each time the event is triggered. This signature does not accept any arguments. This method is a shortcut for .on ( "scroll", handler ) in the first and second variations, and .trigger ( "scroll" ) in the third.

What is the difference between Scroll () and optional scroll () methods?

The scroll () method triggers the scroll event, or attaches a function to run when a scroll event occurs. Optional. Specifies the function to run when the scroll event is triggered How to toggle between classes on different scroll positions.


1 Answers

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/

like image 111
undefined Avatar answered Sep 21 '22 17:09

undefined