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); }); });
click(function(event) { event. preventDefault(); $. scrollTo($('#myDiv'), 1000); });
To scroll to an element, just set the y-position to element. offsetTop . The SmoothScroll.
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.
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".
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With