views:

49

answers:

4

how to have a div that always stay on the screen? Lets say i have a div at the left hand site. When the browser is scroll to the bottom, the div will remain there ONLY when its' top reaches the top edge of browser screen so that it will not be hidden. I am using jquery too.

Thank you.

A: 

You need to invoke .scrollTop() on the window and compare that with the offset top value from that DIV.

$(window).bind('scroll', function(e){
    var $div = $('.top').
        sTop = $(window).scrollTop();

    if($div.offset().top <= sTop)
        $div.css('top', sTop);
    else
        $div.css('top', '100px');
});

Whereas in this example, .top is the element which should stay at top.

Example: http://www.jsfiddle.net/2C6fB/8/

jAndy
I think setting it to `position: fixed` is better than constantly changing the `top` value - constantly changing value can lag and cause flickering and other visual anomalies
Yi Jiang
@Yi Jiang: read the OP's requirement again carefully.
jAndy
@jAndy - No, what I mean is setting it to that after it reach the top edge in the Javascript rather than constantly updating the value, and setting it to change with scroll after the user scrolls back like on this page http://www.blackestate.co.nz/
Yi Jiang
I agree with Yi, it's nicer to just change the `position` to `fixed` when the `scrollTop` is more (or eq.) than `x`. And back to `absolute` when otherwise. (and maybe you also have to switch the `top` from 100 to 0 when going to fixed, depends on desired effect). Do note: IE6 does not support fixed positioning.
CharlesLeaf
A: 

Keep your div position: fixed;

boss
A: 

If you want it to always stay in thesame place, you can use the css property position: fixed; else you can use a combination of $(window).scroll() and .scrollTop(); to detect where your div is in relation to the screen and apply the right positioning.

sjobe
+3  A: 

here is a Good ScreenCast By RemySharp Regarding this Issue

http://jqueryfordesigners.com/fixed-floating-elements/

Demo Page :

http://static.jqueryfordesigners.com/demo/fixedfloat.html

Ninja Dude