How to detect the end of a horizontal scroll in a div?
Use scrollWidth
and width
along with your leftscrollwidth
to get the difference. In your case there is offset of 8
so it will give the difference of 8
it may be because of your padding or margin.
var $elem=$('#scrollquestion');
var newScrollLeft = $elem.scrollLeft(),
width=$elem.width(),
scrollWidth=$elem.get(0).scrollWidth;
var offset=8;
if (scrollWidth- newScrollLeft-width==offset) {
alert('right end');
}
Live Demo
Use the outerWidth() to get the offset including the width like,
var $elem=$('#scrollquestion');
var newScrollLeft = $elem.scrollLeft(),
width=$elem.outerWidth(),
scrollWidth=$elem.get(0).scrollWidth;
if (scrollWidth-newScrollLeft==width) {
alert('right end');
}
Another Demo without using offset
Rohan kumar's answer is correct and works fine, but you can do this without calculating the offset manually
var newScrollLeft=$('#scrollquestion').scrollLeft();
var divWidth = $('#scrollquestion').outerWidth();
var scrollwidth =$('#scrollquestion').get(0).scrollWidth;
if(newScrollLeft === scrollwidth - divWidth){
alert('right end');
}
For my specific case, dangor's solution with the
if ($scrollWidth - $width === $scrollLeft) {
alert('right end');
}
did not work for me because calculating ($scrollWidth - $width) created a very small decimal that made the left-side of the comparison a float, and the right-side ($scrollLeft), an integer. Changing it to the code below works perfect for me.
if (parseInt($scrollWidth - $width) === parseInt($scrollLeft)) {
alert('right end');
}
Try http://jsfiddle.net/trxe4n3u/3/
$(function() {
$('#scrollquestion').scroll( function() {
var $width = $('#scrollquestion').outerWidth()
var $scrollWidth = $('#scrollquestion')[0].scrollWidth;
var $scrollLeft = $('#scrollquestion').scrollLeft();
if ($scrollWidth - $width === $scrollLeft){
alert('right end');
}
if ($scrollLeft===0){
alert('left end');
}
});
});