Search code examples
javascripthtmlcssbackground-color

Change Background Colour Along a Gradient as User Scrolls


I'm trying to get the background colour of the page to change on the gradient between black and white as the user scrolls. The colour will depend on where the user is currently scrolled to on the page if that makes sense? Here's some code I have already however the only problem with it is that when the user hasn't scrolled anywhere the webpage is not black.

function scroll(){
	var body = document.body,
		  html = document.documentElement;
	var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
	var color = Math.round(((body.scrollTop + html.offsetHeight) / height) * 255);
	body.style.backgroundColor = "rgb("+color+","+color+","+color+")";
}
html{
	height: 100%;
}
body{
	height: 200%;
	background: rgb(126,126,126);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

  <body onscroll="scroll()">
    <script src="assets/JS/ScrollEffect.js"></script>
  </body>

</html>


Solution

  • You have to use html.scrollTop instead of body.scrollTop. That's because the html element becomes scrollable. The body element with 200% height overflows html with 100% height, which is the viewport height.

    Body does not scroll here, so you always get body.scrollTop = 0. But html does scroll, so you have to use html.scrollTop.

    The elements body and html sometimes act as if they are one element. That's the case for scrolling behaviour. But sometimes they act as if they are two separate elements. That's the cases in styling with CSS.

    To get from black to white (not grey to white), you have to change var height = html.scrollHeight - html.clientHeight; and var color = Math.round((html.scrollTop / height) * 255);

    To make it work in IE you need to add: <html onscroll="scroll()">

    If you can, you should use jquery though (like Kushtrim suggested).

    function scroll(){
    	var body = document.body,
    		  html = document.documentElement;
    	var height = html.scrollHeight - html.clientHeight;
    	var color = Math.round((html.scrollTop / height) * 255);
    	body.style.backgroundColor = "rgb("+color+","+color+","+color+")";
    }
    html{
    	height: 100%;
    }
    body{
    	height: 200%;
    	background: rgb(0,0,0);
    }
    <!DOCTYPE html>
    <html lang="en" dir="ltr" onscroll="scroll()">
    
      <body onscroll="scroll()">
        <script src="assets/JS/ScrollEffect.js"></script>
      </body>
    
    </html>