CSS & Javascript: Change Background Color on Scroll

Last updated on September 1, 2022 Pennywise Loading... 2 comments

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

Example Preview

The full 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>KindaCode.com</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 KindaCode.com</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. Further reading:

You can also check out our CSS category page for the latest tutorials and examples.

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
javi
javi
1 month ago

Nice, but if you scroll fast it doesn’t work

A Goodman
Admin
A Goodman
1 month ago
Reply to  javi

It works

You May Also Like