Search code examples
jqueryscrolloffsethorizontal-scrolling

Check when scrolled to the right


I want to be able to detect if a user has scrolled through an entire div with overlfow:scroll; the div is horizontal though, so using offset().top doesn't work here.
I currently have this code:

var elem = $('#slide');
var inner = $('#slidecontain');
if ( Math.abs(inner.offset().top) + elem.height() + elem.offset().top >= inner.outerHeight() ) {
  alert('bottom')
}

this works perfectly for checking when I've scrolled to the bottom, but since its a horizontal scroll it fires immediately. How can I switch this? Is offset().left a possibility?

Here's the html, pretty basic:

<div id="slide" style="width: 300px; height: 150px;">
        <div id="slidecontain" style="width: 900px; height: 150px;">
            <div class="slide1" style="width: 300px; height: 150px;"></div>
            <div class="slide2" style="width: 300px; height: 150px;"></div>
            <div class="slide3" style="width: 300px; height: 150px;"></div>
        </div>
<div>

Solution

  • It can be easly done with jQuery using .scrollLeft()

    var elem = $('#slide');
    var inner = $('#slidecontain');
    
    elem.scroll(function() {
       if(elem.scrollLeft() + elem.width() == inner.width()) {
           alert("reached end!");
       }
    });
    

    Here is a fiddle simulating this.