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>
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.
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, whileElement.scrollWidth
andElement.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With