Lazy loading conflicting with ScrollTo anchor to ID scroll -answer and response

31 Views Asked by At

I read this ticket: Lazy loading conflicting with ScrollTo anchor to ID scroll - Stops halfway through the page

For those who have problems with these links which only work on the second click, here is a full javascript solution which is functional. It also includes a bit of the solution given at the end.

const arrAnchor = Array.from(document.querySelectorAll('.c-ultro-blocks a')).filter(t=>t.href.includes('#'))

if(arrAnchor.length > 0) {
    let elemTarget = null
    let offsetElement = 0
    let tmOutObserver = null
    let prevPosition = null

    const goLink = (evt) => {
        const id = evt.target.href.split('#').pop()

        elemTarget = document.getElementById(id)

        if(!elemTarget) {
            return
        }

        offsetElement = elemTarget.offsetTop

        window.scrollTo({
            top: offsetElement - 120,
            left: 0,
            behavior: "smooth"
        })

        tmOutObserver = setTimeout(checkScroll, 20)
    }

    const scrollDone = () => {
        offsetElement = elemTarget.offsetTop
        if (offsetElement > window.scrollY + 120) {
            window.scrollTo({
                top: offsetElement - 120,
                left: 0,
                behavior: "smooth"
            })
            prevPosition = null
            checkScroll()
        }
    }

    const checkScroll = () => {
        if (window.scrollY === prevPosition) {
            scrollDone()
            return
        }
        prevPosition = window.scrollY
        tmOutObserver = setTimeout(checkScroll, 20)
    }

    arrAnchor.forEach(aElem => {
        aElem.addEventListener('click', goLink)
    })
}

  • this is the question and one solution
0

There are 0 best solutions below