Reputation: 23
How to count mouse scroll in jquery/javascript? Like initial value 0 and scroll down ++1 and scroll up --1. And not be -1. Must be positive.
If i scroll 2 times down then value will be 2 and then scroll one time up then value be 1.
Upvotes: 1
Views: 13593
Reputation: 147
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function () {
$('html, body').animate({ scrollTop: 0 }, 800);
return false;
});
Upvotes: 0
Reputation: 2055
scrollcount=0;
$(document).ready(function(){
$("div").scroll(function(){
$("span").text(scrollcount+=1);
});
});
Upvotes: 0
Reputation: 561
$(document).ready(function(){
var scrollPos = 0;
var Counter = 0;
$(window).scroll(function(){
var scrollPosCur = $(this).scrollTop();
if (scrollPosCur > scrollPos) {
Counter -= 1;
} else {
Counter += 1;
}
scrollPos = scrollPosCur;
});
});
The code compares the position of a scrollbar. scrollPos
shows how many pixels you moved the scrollbar downwards and is initialized with a value of 0
, as it starts at the top.
When you scroll the page, scrollPosCur
will first save the current Position of the scrollbar. After that we compare how the value changed :
If the current value is bigger than the saved one, it indicates that the scrollbar has been moved downwards, so your Counter
is incremented by 1
.
Analogous to that, we decrement the Counter
by 1
when scrollPosCur
is smaller than scrollPos
.
In order to keep the code working, we save the current value to compare against for future scroll Events.
Upvotes: 2
Reputation: 5577
Here is a possible solution for your question
var scrollCount = 0,
latestScrollTop = 0,
doc = document.documentElement,
top = 0;
// Bind window scroll event
$(window).bind('scroll', function (e) {
top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
if (latestScrollTop < top) {
// Scroll down, increment value
scrollCount += 1;
} else {
// Scroll up, decrement value
scrollCount -= 1;
}
// Store latest scroll position for next position calculation
latestScrollTop = top;
});
Upvotes: 0