Rainbow Scroll

kolja

Kolja

Posted on September 7, 2022

Rainbow Scroll

Simple and fun idea:

The color of the headings (or whatever) changes depending on how far the page was scrolled down.

This function gives us the percentage value:

function getScrollPercent() {
    var h = document.documentElement,
        b = document.body,
        st = 'scrollTop',
        sh = 'scrollHeight';
    return (h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight) * 100;
}
Enter fullscreen mode Exit fullscreen mode

We have to multiply that by 3.6 so that we have the HSL circle complete.

Then just an event listener:

var r = document.querySelector(':root'); 

document.addEventListener('scroll', (e) => {
    let percent = getScrollPercent();
    let hsl = Math.round(percent * 3.6); 
    r.style.setProperty('--rainbowColor', 'hsl(' + hsl + ', 70%, 50%)');
})
Enter fullscreen mode Exit fullscreen mode

And the corresponding CSS:

:root {
    --rainbowColor: hsl(0, 100%, 50%);
}

h1,h2,strong {
    color: var(--rainbowColor);
}
Enter fullscreen mode Exit fullscreen mode

Try it out

Repo

💖 💪 🙅 🚩
kolja
Kolja

Posted on September 7, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Rainbow Scroll
css Rainbow Scroll

September 7, 2022