0

How to execute a function when user scroll past some some mark. say 100px above the page bottom

This is what I got

const onScroll = (e) => {
    let scrollHeight, totalHeight
    scrollHeight = document.body.scrollHeight
    totalHeight = window.scrollY + window.innerHeight
    if (totalHeight >= scrollHeight) {
        // do stuff
    }
}
const DetectScrollBottom = () => {
    useEffect(() => {
        window.addEventListener('scroll', onScroll, false)
        return () => window.removeEventListener('scroll', onScroll, false)
    }, [])
    return <div></div>
}

Problem is, this executes function A at when scroll reaches bottom. not 100px above bottom.

angry kiwi
  • 10,730
  • 26
  • 115
  • 161

2 Answers2

0
if (totalHeight === scrollHeight-100) {
  // Your code here
}

When scroll reaches 100px above the bottom your code will trigger. You can also check here for some reference about scrollHeight.

There is also a related question about it on SO and it is worth to take a look at it here.

Aras
  • 1,599
  • 15
  • 25
Luiz Mariz
  • 58
  • 5
0
const DetectScrollBottom = () => {
    useEffect(() => {
        window.addEventListener('scroll', onScroll, false)
        return () => window.removeEventListener('scroll', onScroll, false)
    }, [])
    let base
    const onScroll = (e) => {
        let scrollHeight, totalHeight
        scrollHeight = document.body.scrollHeight
        totalHeight = window.scrollY + window.innerHeight

        if (totalHeight <= scrollHeight - 401) {
            base = false
        }
        if (totalHeight >= scrollHeight - 400) {
            if (base == true) return
            // run function A here
            base = true
        }
    }
    return <div></div>
}
angry kiwi
  • 10,730
  • 26
  • 115
  • 161