JQuery - Scrolling function continues to run: only once

I have the following jQuery function that runs aTestEvent() when the user scrolls horizontally over 500 pixels:

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

Here's the problem: I want aTestEvent() to aTestEvent() once! However, every time the user scrolls back to the beginning of the page, and then again for 500 pixels, aTestEvent() fires again.

How can we configure the above code so that the trigger appears only for the first time , the user scrolls over 500 pixels?

+6
source share
1 answer

You can use the on and off methods:

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

http://jsfiddle.net/3kacd/

Please note: this piece of code can β€œdisable” all scroll events available on a specific page, but we can use a namespace to scroll only the intended scroll handler without violating other scroll handlers. Namespaces are similar to CSS classes because they are not hierarchical; only one name is required.

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

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

+14
source

Source: https://habr.com/ru/post/945973/


All Articles