Javascript: Change Background Color on Scroll

Updated: March 8, 2023 By: Goodman Post a comment

The example below shows you how to dynamically change the background color of a webpage when the user scrolls down. We only use vanilla Javascript and CSS to make this.

Example Preview

Here’s the demo:

The code

The complete code:

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Sling Academy</title>

    <style>
        * {
            box-sizing: border-box
        }

        body {
            height: 1000vh;
            transition: background 1s ease;
        }

        .content {
            padding: 50px;
            color: white;
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="content">
        <h1>Welcome to Sling Academy</h1>
    </div>

    <script>
        var body = document.getElementsByTagName('body')[0];
        body.style.backgroundColor = 'green';

        // trigger this function every time the user scrolls
        window.onscroll = function (event) {
            var scroll = window.pageYOffset;
            if (scroll < 300) {
                // green
                body.style.backgroundColor = 'green';
            } else if (scroll >= 300 && scroll < 600) {
                // yellow
                body.style.backgroundColor = 'yellow';
            } else if (scroll >= 600 && scroll < 1200) {
                // blue
                body.style.backgroundColor = 'blue';
            } else if (scroll >= 1200 && scroll < 1800) {
                // orange
                body.style.backgroundColor = 'orange';
            } else if (scroll >= 1800 && scroll < 3000) {
                // red
                body.style.backgroundColor = 'red';
            } else {
                // purple
                body.style.backgroundColor = 'purple';
            }
        }
    </script>
</body>

</html>

Explanation

Each time the user scrolls up or down, we call a function that can manipulate the background color:

window.onscroll = function (event) {
  // other code here
}

To calculate the scroll distance, we use this:

var scroll = window.pageYOffset;

To programmatically set the background color, we use this Javascript code:

body.style.backgroundColor = 'green';

to make the color transitions smooth, we add this CSS line:

transition: background 1s ease;

That’s it. Happy coding & have a nice day!