views:

43

answers:

1

Using Jquery preferably, how do I detect if an element is within the viewable client area of a browser?

I'm dynamically creating a menu from a dataset, and when the list grows too long, the height of the resulting menu causes part of it to fall below the browser bottom client area. How do I detect this and act accordingly?

+2  A: 

I believe it should be possible to cook something up using position() and scrollTop() (add scrollLeft if your page is prone to horizontal scrolling). Here is some untested sample code that should display a message if the target element is (fully or partially) within the viewport:

var pos = $('#element').position(), win = $(window);

if (pos.top < win.height() + win.scrollTop() && pos.bottom > win.scrollTop()) {
    alert('Look at me!');
}

The conditions can be swapped around if you care specifically about full visiblity:

if (pos.bottom < win.height() + win.scrollTop() && pos.top > win.scrollTop()) {

Adding support for horizontal scrolling of the viewport is left as an exercise for the reader :)

Jørn Schou-Rode