Detecting That User Has Scrolled To The Bottom Of The Div Without Scroll Event?
Solution 1:
Simply using IntersectionObserver
like the "accepted" answer suggests is not going to work:
const io = new IntersectionObserver(onIntersection, {threshold: 1})
If the element's height is greater than the viewport height then the threshold
won't ever be 1
.
Instead, I found a better solution for variable-height content: insert a 1px
sub-element inside the element being tracked and then track the sub-element instead of the element itself via IntersectionObserver
. This way the onIntersection
callback will be called when a user scrolls down to the bottom of the element.
Solution 2:
Use IntersectionObserver
For this
const onScrollToBottom = document.getElementById('on-scroll-to-bottom')
const onIntersection = ([{isIntersecting, target}]) =>
isIntersecting && (target.style.backgroundColor = 'green');
const io = new IntersectionObserver(onIntersection, {threshold: 1})
io.observe(onScrollToBottom)
section {
color: white;
}
#on-scroll-to-bottom {
margin-top: 100vh;
min-height: 50vh;
background-color: red;
}
#visible {
height: 90vh;
background-color: blue;
}
<section id="visible">Visible Section</section>
<section id="on-scroll-to-bottom">On Scroll to Bottom</section>
Solution 3:
To solve the issue brought up by @catamphetamine that if the element is larger than the viewport it will never reach threshold 1, you could flatten the parent element's bounds to just the bottom of itself and then observe for threshold: 0
and not intersecting instead:
const io = new IntersectionObserver(onIntersection, {
rootMargin: '-100% 0px 0px 0px',
threshold: 0
})
Solution 4:
You can use entry.boundingClientRect
which tells bottom is in viewport or not. If bottom is less than 0, which means above the viewport, also if bottom is greater than window size, which means below the viewport, it's not in view port.
Also threshold check must be on each scroll when it's in viewport, slicing to each 10%.
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const bcr = entry.boundingClientRect;
const isBottomVisible = (bcr.bottom < window.innerHeight) && bcr.bottom;
console.log(bcr.top, bcr.bottom, window.innerHeight, {isBottomVisible});
});
}, {threshold: Array(11).fill().map( (_, i) => i*.1)});
observer.observe(this._templateContainer );
Post a Comment for "Detecting That User Has Scrolled To The Bottom Of The Div Without Scroll Event?"