sir_thursday sir_thursday - 1 year ago 83
jQuery Question

Test in JQuery if an element is at the top of screen

I have a

that is positioned about 100px from the top of the browser window. When the user scrolls down, I want the
to stay where it is until it reaches the top of the screen. Then, I'll change some CSS with JQuery to make the position to change to fixed and the margin-top to 0. How can I test in JQuery if this
is at the top of the screen?

Answer Source
var distance = $('div').offset().top,
    $window = $(window);

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
        // Your div has reached the top

P.S. For better performance, you should probably throttle the scroll event handler.
Check out John Resig's article: Learning from Twitter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download