2

I have this code to change the background color of an element (which works fine)

<script>
window.onscroll = function() {
    if(document.body.scrollTop == 0) {
       jQuery("header#main-header").css('background-color', 'red');
    }
}
</script>

Problem is that I need to set the color to red only if the page scroll is between 0 and 100 and set the color to yellow if is bigger than 100.

I tried this in this page: http://temporal-1.d246.dinaserver.com/ but not working:

<script>
window.onscroll = function() {
    if(document.body.scrollTop <= 99) {
       jQuery("header#main-header").css('background-color', 'red');
    }
    if(document.body.scrollTop >= 100) {
       jQuery("header#main-header").css('background-color', 'yellow');
    }
}
</script>
JPashs
  • 13,044
  • 10
  • 42
  • 65

3 Answers3

2

Well you need to calculate top offset a little differently

window.onscroll = function() {
    var doc = document.documentElement;
    var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
    if(top <= 99) {
       jQuery("header#main-header").css('background-color', 'red');
    }
    else {
       jQuery("header#main-header").css('background-color', 'yellow');
    }
} 
void
  • 36,090
  • 8
  • 62
  • 107
1
jQuery(document).ready(function(){
jQuery("body").css('background-color', 'red');
jQuery(window).scroll(function(){
    if ( jQuery(document).scrollTop() <= 99 ) {
         jQuery("body").css('background-color', 'red');
    } else {
        jQuery("body").css('background-color', 'yellow');
    }
})

})

kamrul
  • 11
  • 1
0

A simple execution for changing an element when you scroll

$(function () {
    $(document).scroll(function() {
        var $nav = $("class name");
        // $nav.height() can be changed to whatever height you want to start the change effect
        $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height()); 
    });
});
adarian
  • 334
  • 7
  • 24
  • 2
    You have an error in your `$nav`. Also, consider adding snippets instead of raw code for frontend functionality, and some explanation to it as well. – wscourge Apr 02 '19 at 05:01