Reputation: 22167
How to detect first top element (who is visible on window view) when scrolling ?
Like this...
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
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");
}
}));
Upvotes: 6
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');
}));
Upvotes: -1