jquery scroll to a px count from top and then set a div to be fixed from the top for the rest of the scroll
Asked Answered
O

4

6

I am looking to change a div's css when i scroll to a certain point down the page, a certain amount of pixels from the top of the page.

On page load i would have a div positioned statically. Once I started to scroll down the page and i hit a point from the top (say 100px for demo purposes) i want to change that static div to become fixed like 20px from the top. Which would be done via the css() property of jquery. THis would allow it to stay at that fixed 20px all the way down the page.

What jquery property can i use to know when i hit that 100px mark. I want this to also revert once someone gets back to the top so that the div is put back to where it was when the page loaded and not 20px from the top.

Any ideas?

Octoroon answered 4/1, 2011 at 19:51 Comment(0)
M
5

You could use the scroll() event to run the code, and the scrollTop() method to see where you are.

Here's a demo: http://jsfiddle.net/EahRx/

(I used the values you provided, so there's a jump. I'm sure it will look better in your actual page.)

var fixed = false;

$(document).scroll(function() {
    if( $(this).scrollTop() >= 100 ) {
        if( !fixed ) {
            fixed = true;
            $('#myDiv').css({position:'fixed',top:20}); // Or set top:20px; in CSS
        }                                           // It won't matter when static
    } else {
        if( fixed ) {
            fixed = false;
            $('#myDiv').css({position:'static'});
        }
    }
});

The fixed variable prevents the .css() code from running more times than it needs to.

Miscellaneous answered 4/1, 2011 at 20:5 Comment(2)
Have you got any idea why this does not work in IE8? Any possible solution?Fairminded
@Florian: Try $(window).scroll(... instead of $(document).scroll(....Miscellaneous
W
1

Try using scrollTop:

$(window).scroll(function(){
    if  ($(window).scrollTop() >= 100){
        //CSS changes go here
    }
});
Wilmoth answered 4/1, 2011 at 20:5 Comment(0)
P
0

Here's a lovely jQuery plug-in that I found that does the trick nicely and gives you some useful additional features, such as setting the offset and changing the css between "attached" and "detached" mode.

http://code.google.com/p/sticky-panel/

Proudfoot answered 17/7, 2012 at 19:26 Comment(0)
M
0

I just found this. I think this is really interesting; I liked it.

Markowitz answered 1/8, 2013 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.