Search code examples
javascriptjquerycssbackground-color

Change background of fixed header when scrolling past elements


I'm trying to get the background-color of my fixed header to change upon scrolling over certain DIV sections on the page, similar to this:

http://www.adamrudzki.com/

The sections I'm using don't have a fixed height.

I've found this similar question Change background-color while scrolling

( which uses this fiddle http://jsfiddle.net/cEvJk/18/ )

var t = $('#about').offset().top - 100;

$(document).scroll(function(){
    if($(this).scrollTop() > t)
    {   
        $('header').css({"background-color":"green"});
    } 
});

But I'm unable to get the effect to repeat for all sections.


Solution

  • Try this :

    var t = $('#about').offset().top - 100;
    var t1 = $('#work').offset().top - 100;
    
    $(document).scroll(function(){
        if($(this).scrollTop() > t1) {   
            $('header').css({"background-color":"blue"});
        } else if($(this).scrollTop() > t) {   
            $('header').css({"background-color":"green"});
        } else {
            $('header').css({"background-color":"#520833"});
        }
    });
    

    And so on with var t2 = ....

    Don't forget to put higher values on top of the if's