2

I want to make an background color animation change when the user gets to the specific section.

Here is the jQuery code I wrote:

var initialColors = [];

$('section.changecolorbg').each(function(i){
  initialColors[i] = $(this).css("backgroundColor");
});

$(window).scroll(function() {
  $('section.changecolorbg').each(function(i){
    if(isScrolledIntoView($(this))){

      var bgc = initialColors[i];

      $(this).parent().children('.changecolorbg').each(function(){
        $(this).css("backgroundColor", bgc);
      });

    }
  })
});

function isScrolledIntoView(elem)
{
  var hT = elem.offset().top,
       hH = elem.outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop() + 200;

   return (wS > (hT+hH-wH))
}

The sections will have a background-color initially, this is why I saved them in a variable. The problem with this is that it's working pretty slow. I think is that because all the checking needs to be done in the .scroll function.

Is there a way I can improve the code?

P.S. The effect I'm trying to achieve is same as on http://sfcd.com/

Florin Pop
  • 5,105
  • 3
  • 25
  • 58
  • 2
    You're right in your diagnosis - the slowdown issue is because that the `scroll()` handler fires once for every pixel the UI updates as you scroll. To improve the speed you can [debounce](http://stackoverflow.com/questions/9144560/jquery-scroll-detect-when-user-stops-scrolling) the event. However, this induces some lag, which may not work for you. There's no real alternative though, other than minor code optimisations. – Rory McCrossan Nov 18 '16 at 11:28

1 Answers1

0

You can try something like this using hsl colors in CSS (hue, saturation, lightness) and deriving the hue value from the window.scrollY position:

var body = document.getElementsByTagName('body')[0];

function changeHue() {
    var hue = (window.scrollY / 20);
    body.style.backgroundColor = 'hsl('+hue+', 100%, 50%)';
}

window.addEventListener('scroll', changeHue, false);
body {
background-color: hsl(0,100%,50%);
}

div {
height: 10000px;
}
<div></div>
Rounin
  • 27,134
  • 9
  • 83
  • 108