dhruveonmars
dhruveonmars

Reputation: 409

JQuery Add Class when bottom of div reaches top

I am trying to add a class when the bottom of a div reaches the top of the window, but am not sure of how to do it. I have managed to add the class when the top of the div gets to the top of the window, but am not having much luck with the bottom of the div.

Code I am using:

$(document).ready(function() {  
var menuLinksTop = $('.container').offset().top;  

var menuLinks = function(){  
    var scrollTop = $(window).scrollTop();  

    if (scrollTop > menuLinksTop) {   
        $('header').addClass('black-links');  
    } else {
        $('header').removeClass('black-links');   
    }
};

menuLinks();  

$(window).scroll(function() {  
    menuLinks();  
});

Any help is appreciated.

Upvotes: 1

Views: 3937

Answers (2)

r---------k
r---------k

Reputation: 977

You should use javascript's getBoundingClientRect() method, watch $(window).scroll event, and look at element's rectangle, its bottom value will give you what you need (if it's negative, your element is all the way up)

$(window).scroll(function() {
    console.log($("div.watch")[0].getBoundingClientRect());
    if ($("div.watch")[0].getBoundingClientRect().bottom < 0)
        alert ("i'm out :3");
});

see jsFiddle http://jsfiddle.net/ja5nnbwr/2/

Upvotes: 4

Brewal
Brewal

Reputation: 8189

Add the height of the div. Assuming it is the .container :

var menuLinksTop = $('.container').offset().top + $('.container').height();

Upvotes: 1

Related Questions