Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 687
Sam Murphey Avatar asked Sep 19 '25 11:09

Sam Murphey


2 Answers

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.

like image 53
Claudio Holanda Avatar answered Sep 21 '25 14:09

Claudio Holanda


If anyone is looking for a React based solution, you can try this out:

const containerRef = React.useRef<HTMLDivElement>(null);
const isScrolledRight = () => {
  if (containerRef.current) {
    const { current } = containerRef;
    return Math.abs(current.scrollWidth - current.clientWidth - current.scrollLeft) <= 1;
  }
  return false;
};

return(
  <div className='cardContainer' ref={containerRef}>
    <div className='card'><p>card text</p></div>
    <div className='card'><p>card text</p></div>
    <div className='card'><p>card text</p></div>
    <div className='card'><p>card text</p></div>
  </div>
)

CSS:

.cardContainer {
  flex-direction: row;
  width: 160px;
  display: flex;
  overflow-x: auto;
}
.card {
  width: 120px;
  height: 100px;
  flex: 0 0 auto;
}

Element.scrollLeft is a non-rounded number, while Element.scrollWidth and Element.clientWidth are rounded - so the only way to determine if the scroll area is scrolled to the bottom is by seeing if the scroll amount is close enough to some threshold (i.e. 1 in this case).

Reference: Scroll height

like image 40
Sabbir Ahmed Avatar answered Sep 21 '25 14:09

Sabbir Ahmed