Change the background color of an element when scrolling the page

-1

I have tried this code without success.

$(document).ready(function(){
  $(document).scroll(function() {
    var alpha = Math.min(0.5 + 0.4 * $(this).scrollTop() / 210, 0.9);
    var channel = Math.round(alpha * 255);
    $(\"body\").css('background-color', 'rgb(' + channel + ',' + channel + ',' + channel + ')');
  });
});

My codes

CSS

header {
 background-color: #0683c9;
}

Element that I want to change the color header

 <header>
    <div id=\"logo\">
     ......
     ......
 </header>
    
asked by anonymous 06.04.2017 / 13:31

2 answers

2

As @Leo Letto commented, you are applying color to the body and not the header, here is a working example of your code.

$(document).ready(function() {
  $(document).scroll(function() {
    var alpha = Math.min(0.5 + 0.4 * $(this).scrollTop() / 210, 0.9);
    var channel = Math.round(alpha * 255);
    $("header").css('background-color', 'rgb(' + channel + ',' + channel + ',' + channel + ')');
  });
});
body {
  height: 800px;
  background-color: black;
}

header {
  background-color: #0683c9;
  width: 100%;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body><header><divid="logo"></div>

  </header>
</body>
    
06.04.2017 / 13:39
4

Try this:

    window.onscroll = function (e) {  
      document.getElementById("header").style.backgroundColor = "red";
    } 
header {
     background-color: #0683c9;
     width:600px;
     height: 1200px;
    }
<header id="header">
    <div>
    </div>
 </header>

You have this example working on this link:   link

    
06.04.2017 / 13:45