Change the background color of an element when scrolling the page

Asked

Viewed 1,145 times

-1

I’ve tried that code without succeeding.

$(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 I want to change color header

 <header>
    <div id=\"logo\">
     ......
     ......
 </header>
  • 2

    But in your code you are applying the color to the body and not to the header

2 answers

4

Try it this way:

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

Have this example working on this link: https://jsfiddle.net/Lm7j4tvr/

  • While this link may answer the question, it is best to include the essential parts of the answer here and provide the link for reference. Replies per link only can be invalidated if the page with the link is changed. - Of Revision

  • I edited the answer.

1


As @Leo Letto commented, you are applying the color to the body and not the header, follow a functional 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>
    <div id="logo"></div>

  </header>
</body>

  • I had put header, in the script, at the time of formulating the question pasted wrong. But it was of great value your answer because I saw in your example that the script should be placed after the tag. Even worth!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.