Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change div css when user scrolls past it, using jQuery

When a user scrolls past a div I need it's css changed to position:fixed. Much like what is done here: http://imakewebthings.com/jquery-waypoints/shortcuts/sticky-elements/ but with just plain jquery, without the plugin.
The div must also stop scrolling once the user scrolls to another div.
For example:

<div id="stuff"></div>
<div id="this"></div>//must start scrolling with user when user reaches it.
<div id="footer"></div>// when #this reaches within say, 10px, of #footer it must stop in it's current position, in order to prevent overlap

I'm assuming i'd use .scroll() and .css(), but I have no idea where to go from there.

like image 941
Atom Vayalinkal Avatar asked Dec 04 '25 16:12

Atom Vayalinkal


2 Answers

I noticed in your answer #this disappears abruptly once you get down to #footer. I've tweaked your answer to allow for #this to stick to #footer and scroll which is a lot smoother.

My demo uses slightly different markup and is a little more verbose so jump over to jsFiddle and check it out.

Demo: jsfiddle.net/Marcel/e9hyw/

like image 195
Marcel Avatar answered Dec 07 '25 01:12

Marcel


This is what finally worked for me:

    jQuery(document).ready(function() {
    var topOfrel = jQuery("#this").offset().top;
    var topOffooter = jQuery("#footer").offset().top - jQuery(window).height(); 
    var topOffootero = topOffooter ;
    var boxheight = jQuery(window).height() - 130;//adjusting for position below
    jQuery(window).scroll(function() {
        var topOfWindow = jQuery(window).scrollTop();
        if (topOfrel < topOfWindow && topOffooter > topOfWindow) {
            jQuery("#this").css("position", "fixed").css("top", "130px").css("overflow","auto").css("height", boxheight + "px");

        } else {
            jQuery("#this").css("position", "static");
        }
    });
});
like image 37
Atom Vayalinkal Avatar answered Dec 07 '25 01:12

Atom Vayalinkal