Hi, I'm trying to implement a basic ScrollTrigger animation on Nextjs. It's basically changing sidebar background based on current position of scroll. You can check it's implementation here: Introduction - Budget Basics | Open Budgets India.
Problem is initial load of page, which messes up the the start/end of scrolltrigger but resizing the browser fixes the position. I tried some solutions from this post: ScrollTrigger Unexpected Behavior with Smooth Scrollbar in React/NextJs - GSAP - GreenSock but they are not working in my case.
All of the code is available here: budget-basic-next/[chapter].js at main · PixeledCode/budget-basic-next (github.com) but basically what I'm doing is
useEffect(() => {
gsap.registerPlugin(ScrollTrigger)
setTimeout(handleSidebarAnimation, 100)
return () => {
ScrollTrigger.refresh()
if (ScrollTrigger.getById('st-id')) {
ScrollTrigger.getById('st-id').kill()
}
}
}, [])
and the function is
function handleSidebarAnimation() {
const articles = gsap.utils.toArray('article')
articles.forEach((article) => {
let sideLink = document.querySelector(
`li[keyid=${article.getAttribute('id')}]`
)
gsap.to(sideLink, {
scrollTrigger: {
markers: true,
trigger: article,
id: 'st-id',
start: 'top 22%',
end: 'bottom 18%',
refreshPriority: 1,
toggleActions: 'restart complete reverse reset',
onEnter() {
sideLink.classList.add('activeSidebar')
},
onLeave() {
sideLink.classList.remove('activeSidebar')
},
onEnterBack() {
sideLink.classList.add('activeSidebar')
},
onLeaveBack() {
sideLink.classList.remove('activeSidebar')
},
},
})
})
}
I know I'm probably doing something wrong and it's dom order which is creating issues on initial load (eg: coming from home page to the page with sidebar and animation.) but I am not able to find where. Any help is appreciated!