#How to make the navbar change color when it's sticky like in the Solidjs homepage?

4 messages · Page 1 of 1 (latest)

fallow bane
#

I only could come up with this. 400 is a fixed value for now, I should probably change it. Any suggestions?


  const changeBgColorHandler = () => {
    if (window.scrollY >= 400) {
      setBgColor(true);
    } else {
      setBgColor(false);
    }
  };

  window.addEventListener("scroll", changeBgColorHandler);
pliant jolt
#

Here's a quick snippet from a similar feature I made where I change the opacity based on percentage scrolled of the screen.

  const [percentageScrolled, setPercentageScrolled] = createSignal(0); 
   let handlingScroll = false; 
   onMount(() => { 
     document.addEventListener( 
       "scroll", 
       () => { 
         if (!handlingScroll) { 
           handlingScroll = true; 
           window.requestAnimationFrame(() => { 
             const p = Math.min(Math.round((window.scrollY / window.innerHeight) * 100) / 100, 1); 
             setPercentageScrolled(p); 
             handlingScroll = false; 
           }); 
         } 
       }, 
       { passive: true } 
     ); 
   });

You may also be interested in the Solid Primitive useWindowScrollPosition which abstracts some of these performs considerations away. Especially useful if you plan doing more with scroll positions in other components because it creates a single listener to be used in other places.

https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#useWindowScrollPosition

Chrome Developers

Learn how to improve your page's scrolling responsiveness by avoiding
passive event listeners.

The window.requestAnimationFrame() method tells the
browser that you wish to perform an animation and requests that the browser calls a
specified function to update an animation right before the next repaint. The method takes a
callback as an argument to be invoked before the repaint.

GitHub

A library of high-quality primitives that extend SolidJS reactivity. - solid-primitives/packages/scroll at main · solidjs-community/solid-primitives

fallow bane