jQuery - Scroll Function Keeps Triggering: Only Once Please

后端 未结 1 698
别那么骄傲
别那么骄傲 2021-02-09 12:38

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

jQuery(document).scroll(functio         


        
相关标签:
1条回答
  • 2021-02-09 12:59

    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/

    0 讨论(0)
提交回复
热议问题