change css when user scroll past or below a specific div

lee picture lee · Sep 21, 2015 · Viewed 16.7k times · Source

look here: http://jsfiddle.net/1L5y559z/

Let's say I want to change the body's background color when someone scroll past or below div 1, how would I do that with jquery if it can?

I know there's this:

$(window).scroll(function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 100;

if(y_scroll_pos > scroll_pos_test) {
   $("body").css("background-color","black");
}
else
{
   $("body").css("background-color","white");
}
});

But it's for when you scroll past or below a specific number pixel. I'm trying to get the same thing for a specific div instead.

Answer

Gregg Duncan picture Gregg Duncan · Sep 21, 2015

It's the same sort of thing. you just have to determine how far the top of the div is from the top of the window. Then determine the height of the div add the two together to get the pixel distance from the top where you want the change to occur. Then when you scroll past that point you make the change.

$(function(){
    $(window).scroll(function() {
        var scroll = $(window).scrollTop(); // how many pixels you've scrolled
        var os = $('#div1').offset().top; // pixels to the top of div1
        var ht = $('#div1').height(); // height of div1 in pixels
        // if you've scrolled further than the top of div1 plus it's height
        // change the color. either by adding a class or setting a css property
        if(scroll > os + ht){
            $('#div2').addClass('blue');
        }
    });
});

see this fiddle: http://jsfiddle.net/5d922roc/