Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make div follow scrolling smoothly with jQuery?

Tags:

jquery

scroll

In my container there are sections/boxes, but the last one of these boxes should follow scrolling when none of the other boxes are visible.

So, when user scrolls down, he sees a normal sidebar, but when user has went down enough, sidebar ends but the last box starts to follow on the top of the screen. I have seen this a lot on different kind of sites.

My code at the moment:

$(window).scroll(function(){     $.each($('.follow-scroll'),function(){         var eloffset = $(this).offset();         var windowpos = $(window).scrollTop();         if(windowpos<eloffset.top) {             var finaldestination = 0;         } else {             var finaldestination = windowpos;         }         $(this).stop().animate({'top':finaldestination},200);     }); }); 
like image 257
Martti Laine Avatar asked Feb 01 '10 15:02

Martti Laine


People also ask

How do I smooth a div scroll?

click(function(event) { event. preventDefault(); $. scrollTo($('#myDiv'), 1000); });

How do I smooth a scroll to an element?

To scroll to an element, just set the y-position to element. offsetTop . The SmoothScroll.

How do I horizontally scroll a div using jQuery?

In jQuery, we can make any element tag move horizontally using the built-in function scrollLeft() function for scrolling the scrollbar horizontally according to either the position which is set as the parameter or without setting the position which would specify the position in pixel number of the scrollbar.


2 Answers

There's a fantastic jQuery tutorial for this at https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/.

It replicates the Apple.com shopping cart type of sidebar scrolling. The Google query that might have served you well is "fixed floating sidebar".

like image 27
S Pangborn Avatar answered Sep 23 '22 06:09

S Pangborn


Since this question is getting a lot of views and the tutorial linked in the most voted answer appears to be offline, I took the time to clean up this script.

See it live here: JSFiddle

JavaScript:

(function($) {     var element = $('.follow-scroll'),         originalY = element.offset().top;      // Space between element and top of screen (when scrolling)     var topMargin = 20;      // Should probably be set in CSS; but here just for emphasis     element.css('position', 'relative');      $(window).on('scroll', function(event) {         var scrollTop = $(window).scrollTop();          element.stop(false, false).animate({             top: scrollTop < originalY                     ? 0                     : scrollTop - originalY + topMargin         }, 300);     }); })(jQuery); 
like image 146
Martti Laine Avatar answered Sep 23 '22 06:09

Martti Laine