Reputation: 2282
I need to trigger when user stop scrolling and alert some message. But I need to trigger it by percent.
For example I want to alert to user some message if he scroll, but when he stop scrolling and if he scroled more then 80% of window.
I have this code which trigger when srcoll is stopped and don't know how to get this work with scroll percen:
$.fn.scrollStopped = function(callback) {
$(this).scroll(function(){
var self = this, $this = $(self);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
$this.data('scrollTimeout', setTimeout(callback,250,self));
});
};
jQuery(window).scrollStopped(function(){
alert('stopped');
});
Upvotes: 0
Views: 405
Reputation: 15249
You can calculate the height of document and window, and then compare it with the current vertical position of the scroll bar:
$.fn.scrollStopped = function(callback) {
$(this).scroll(function(){
var self = this, $this = $(self);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
$this.data('scrollTimeout', setTimeout(callback,250,self));
});
};
jQuery(window).scrollStopped(function(){
console.log(jQuery(window).scrollTop());
if($(window).scrollTop() > ($(document).height() - $(window).height())*0.8){
alert('You have scrolled more than 80%');
}
});
Try it yourself. You probably want to read more details about both functions; .scrollTop() and .height().
Upvotes: 2
Reputation: 5745
DEMO: http://jsfiddle.net/A9dB2/
jQuery(window).scrollStopped(function(){
var docH = $(document).height();
var winH = $(window).height();
var scrollTop = $(this).scrollTop()
var totalPixels = docH - winH;
var scrollPercentage = parseFloat(scrollTop/totalPixels * 100).toFixed(2);
alert(scrollPercentage + "%");
});
Upvotes: 1