Michael Bole
Michael Bole

Reputation: 27

Change Background-color on scroll

I'm wanting to create an effect like the one on the following page http://readymag.com/ where the background color changes depending on the scroll position but have no idea how to go about it and I can't understand their code.

I've seen a few examples that change from 1 color to another but I'm unsure how to do it with multiple colors. (I would like to be able to specify each color)

Any help would be greatly appreciated.

Michael.

Upvotes: 0

Views: 7540

Answers (1)

Vadim
Vadim

Reputation: 8779

Here is a simple way to do it:

HTML

<body onscroll="scroll()">
  ...
</body>

JavaScript

// HSL Colors
var colors = [
  [0, 100, 50],
  [113, 75, 25],
  [240, 87, 40],
  [328, 24, 40]
],

el = document.getElementsByTagName('body')[0],   // Element to be scrolled
length = colors.length,                          // Number of colors
height = Math.round(el.offsetHeight / length);   // Height of the segment between two colors

function scroll() {
  var i = Math.floor(el.scrollTop / height),     // Start color index
      d = el.scrollTop % height / height,        // Which part of the segment between start color and end color is passed
      c1 = colors[i],                            // Start color
      c2 = colors[(i+1)%length],                 // End color
      h = c1[0] + Math.round((c2[0] - c1[0]) * d),
      s = c1[1] + Math.round((c2[1] - c1[1]) * d),
      l = c1[2] + Math.round((c2[2] - c1[2]) * d);
  el.style['background-color'] = ['hsl(', h, ', ', s+'%, ', l, '%)'].join('');
}

Working example: http://jsbin.com/elolud/2/edit

Upvotes: 2

Related Questions