Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Scrolling at a Certain Point

Tags:

jquery

I'm trying to replicate something similar to this .

When you scroll down, the div scrolls with you (position: fixed) until it reaches a certain point, where it stops (position: absolute), and as you continue to scroll down, it retains that position on the page (250px), until you scroll up to pick it back up again.

What I have so far.

Right now my fiddle does everything except it does not retain the position it was "dropped off" at, instead it goes back to its original position.

Ideas?

like image 577
Aaron Avatar asked May 23 '26 05:05

Aaron


1 Answers

You need to calculate the scrollTop value of the window and then apply that as the value for top and set position to absolute.

$('element').css({
    'top': $(window).scrollTop(),
    'position': 'absolute'
});

As you keep scrolling though the scrollTop value will change, so you must only do this once. Use a variable to keep track of what state the element is in. As far as I can tell, there are three:

  1. Relative
  2. Fixed
  3. Absolute

With this variable you can also reduce the strain on the browser by only setting a class when it is needed. For example:

if( y > 100 && pos != 'fixed' ){

    pos = 'fixed';

    $('element').addClass('fixed');

}else if( y > 100 && pos != 'relative' ){

    pos = 'relative';

    $('element').addClass('relative');

}

Hope that helps :)

like image 64
will Avatar answered May 25 '26 19:05

will



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!