Reputation:
How to detect scroll only once per user request. My first attempt looks like this:
$(window).bind('mousewheel', function(event) {
console.log("hello")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<image src="https://www.setaswall.com/wp-content/uploads/2017/10/Beautiful-Wallpaper-1080x2160.jpg"></image>
The problem with the above code is that when the user scrolls the function doesnt fires continuesly rather than just detecting it once and printing the console.log once.
My second attempt:
$(this).one('scroll', function(){
// scroll
console.log("hello")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<image src="https://www.setaswall.com/wp-content/uploads/2017/10/Beautiful-Wallpaper-1080x2160.jpg"></image>
The problem with the second attempt is that the function fires only one time unless the page is refreshed.
How can I make my second attempt better so that it detects more than one time
without refreshing the page? If I scroll down I want hello to be displayed only once and when I scroll up again I want hello to be displayed once again
Upvotes: 0
Views: 1918
Reputation: 8406
var currentScrollTop = 0,
previousScrollDir = true;
$(this).scroll(function () {
var scrollTop = $(this).scrollTop();
if (scrollTop < currentScrollTop) {
if (!previousScrollDir) {
console.log('scrolled up');
previousScrollDir = true;
}
} else {
if (previousScrollDir) {
console.log('scrolled down');
previousScrollDir = false;
}
}
currentScrollTop = scrollTop;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<image src="https://www.setaswall.com/wp-content/uploads/2017/10/Beautiful-Wallpaper-1080x2160.jpg"></image>
Upvotes: 1
Reputation: 974
Set the scroll eventListener and then unbind it on scroll:
$(window).on("scroll", function(e){
console.log("only alerting once");
$(window).unbind("scroll");
});
Upvotes: 2