469,926 Members | 1,497 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,926 developers. It's quick & easy.

jQuery Scroll follow

Mads Klitgaard
I have a sort of sidebar on my website, which has to scroll down together with the user so that it is always in the view.

The code I'm using now is actually working fine however there is one problem. On smaller screens the sidebar scrolls before your at the sidebar thus making it impossible to see it all even if you scroll.

So what I want is the sidebar to scroll with the bottom instead of it being pushed down with the top so that when you reach the end of the sidebar it starts to scroll.

This is the code that I'm currently using.

Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.     var documentHeight = 0;
  3.     var topPadding = 10;
  4.     $(function() {
  5.         var offset = $("#mainright").offset();
  6.         documentHeight = $(document).height();
  7.         $(window).scroll(function() {
  8.             var sideBarHeight = $("#mainright").height();
  9.             if ($(window).scrollTop() > offset.top) {
  10.                 var newPosition = ($(window).scrollTop() - offset.top) + topPadding;
  11.                 var maxPosition = documentHeight - (sideBarHeight);
  12.                 if (newPosition > maxPosition) {
  13.                     newPosition = maxPosition;
  14.                 }
  15.                 $("#mainright").stop().animate({
  16.                     marginTop: newPosition
  17.                 });
  18.             } else {
  19.                 $("#mainright").stop().animate({
  20.                     marginTop: 0
  21.                 });
  22.             };
  23.         });
  24.     });
  25. </script>
  26.  
Oct 13 '10 #1
1 2311
acoder
16,027 Expert Mod 8TB
Can you not use "position:fixed" instead?
Oct 14 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by DuaneMoraes | last post: by
1 post views Thread by mikeh3275 | last post: by
20 posts views Thread by Aaron Gray | last post: by
7 posts views Thread by dark | last post: by
26 posts views Thread by RobG | last post: by
2 posts views Thread by souporpower | last post: by
53 posts views Thread by souporpower | last post: by
5 posts views Thread by jrod11 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.