DEV Community 👩‍💻👨‍💻


Posted on • Originally published at

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);'--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


Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!