Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  162] [ 2]  / answers: 1 / hits: 168934  / 7 Years ago, wed, august 9, 2017, 12:00:00

I have a website with different sections. I am using segment.io to track different actions on the page. How can I detect if a user has scrolled to the bottom of a div? I have tried the following but it seems to be triggered as soon as I scroll on the page and not when
I reached the bottom of the div.



componentDidMount() {
document.addEventListener('scroll', this.trackScrolling);
}

trackScrolling = () => {
const wrappedElement = document.getElementById('header');
if (wrappedElement.scrollHeight - wrappedElement.scrollTop === wrappedElement.clientHeight) {
console.log('header bottom reached');
document.removeEventListener('scroll', this.trackScrolling);
}
};

More From » reactjs

 Answers
7

you can use el.getBoundingClientRect().bottom to check if the bottom has been viewed



isBottom(el) {
return el.getBoundingClientRect().bottom <= window.innerHeight;
}

componentDidMount() {
document.addEventListener('scroll', this.trackScrolling);
}

componentWillUnmount() {
document.removeEventListener('scroll', this.trackScrolling);
}

trackScrolling = () => {
const wrappedElement = document.getElementById('header');
if (this.isBottom(wrappedElement)) {
console.log('header bottom reached');
document.removeEventListener('scroll', this.trackScrolling);
}
};

[#56820] Monday, August 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keric

Total Points: 572
Total Questions: 93
Total Answers: 97

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;