l2aelba
l2aelba

Reputation: 22167

Detect first top element when scrolling

How to detect first top element (who is visible on window view) when scrolling ?

Like this...

detect first top element

I begin with..

$(window).scroll($.debounce(250,function(){
    $('.box').removeClass('current').each(function() {
       //if(statement) {
       //  $(this).addClass('current')
       //}
    });
}));

Playground : http://jsfiddle.net/l2aelba/EUztW/

I have no idea how to detect which first box is on top.

Upvotes: 2

Views: 433

Answers (2)

James Montagne
James Montagne

Reputation: 78650

$(window).scroll($.debounce(250, function(){
    var scrollTop = $(window).scrollTop();
    var $first;
    var firstPos;

    $('.box').each(function() {
            var $box = $(this).removeClass('current');
            var pos = $box.offset();

            if(pos.top > scrollTop && (!firstPos || pos.top < firstPos.top)){
                $first = $box;
                firstPos = pos;
            }
    });

     if($first){
        $first.addClass("current");   
     }
}));

http://jsfiddle.net/EUztW/10/

Upvotes: 6

Jithin
Jithin

Reputation: 2604

You can use .offset() to find the top div.

$(window).scroll($.debounce(250,function(){
    var top_one;
    var offset_top = 10000;
    $('.box').removeClass('current').each(function() {
        offset = $(this).offset();
        if(offset.top < offset_top){
            offset_top = offset.top;
            top_one = $(this);
        }
    });
    top_one.addClass('current');
}));

jsFiddle

Upvotes: -1

Related Questions