Reputation: 1774
I need to know how I can get the first element that is visible in the browser view.
I am implementing a custom scroller. however when the user uses the mouse to scroll my custom scroller messes up. I need to find the visible divs in the visible area in the browser after scrolling, so I will be able to scroll to the right element.
here is the structure of my page:
<div class="page">
<div id="scroller" class="news-scroller">
<div ><span id="up"></span></div>
<div ><span id="down"></span></div>
</div>
<div class="news">
</div>
<div class="news">
</div>
....
</div>
I am using the scroller #up and #down to scroll to the previous or next div.news. (I use scrollTo plugin) but after using the mouse for scroll I need to understand which div.news is the first visible element in the page to reset my custom scroller.
Here is my code in case it helps:
var current = $(".news").eq(0);
$("#down").click(function(){
if(current.next().size() > 0)
{
current = current.next();
$.scrollTo("#"+current.attr("id"), 800);
}
else if(current.next().size() <= 0)
{
return
}
});
$("#up").click(function(){
if(current.prev().size() > 0)
{
current=current.prev();
$.scrollTo("#"+current.attr("id"), 800);
}
else if(current.prev().size() <= 0)
{
return;
}
});
and here is the example page.
Upvotes: 1
Views: 2049
Reputation: 23208
Following code will tell you if element is completely visible.
function isElementVisisble(element) {
element = $(element);
var parent = $(window);
var containerLeft = parent.parent().scrollLeft();
var containerRight = containerLeft + parent.parent().width();
var elemLeft = element.offsetLeft;
var elemRight = elemLeft + $(element).width();
if (elemLeft < containerLeft || elemRight > containerRight) {
return false;
}
return true;
}
You can use
var firstVisibleElem;
jQuery("*").each(function(){
if(isElementVisisble(this)){
firstVisibleElem= this;
return false;
}
});
Upvotes: 2