craftcms

How to change style or add class on scroll in Craft


Hello I am new in craft and I would like to know if there is a possibility to change style or add class on scroll. For example I have fixed navigation and I would like to change a color when user is on 1000px scroll height. How I could do it ?


Solution

  • This has little to do with Craft since it's just a matter of adding some JavaScript code to your frontend. There are a couple of ways to achieve this. The classic way to perform some action on scroll is to use a scroll event listener. Inside the event listener, you can check the scroll position (see window.scrollY) and perform whatever logic you want. The downside is that scroll event listeners are bad for performance, since in theory they can execute many times in a row while scrolling. Some browsers throttle scroll events for this reason, so the event listener may be executed with some delay. You should try to avoid using scroll listeners where possible, or at least use passive listeners to improve performance.

    headroom.js is a library specifically to modify sticky navigations depending on scroll position and direction, though it suffers from the same problem since it uses scroll event listeners.

    If you can, see if your problem can't be solved using Intersection Observers, since their performance is much better.