Help me with this javascript (sticky sidebar widget)?
-
Here’s the “sticky sidebar widget” in action: http://blog.hartleybrody.com/wp-content/uploads/2011/05/sticky-demo.html
As you can see, when you scroll down the widget scrolls with the page. And if you scroll back up it stops at it’s original spot. Pretty cool.
I know nothing about javascript, but here’s the script:
http://blog.hartleybrody.com/creating-sticky-sidebar-widgets-that-scrolls-with-you/
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script> $(document).ready(function() { function isScrolledTo(elem) { var docViewTop = $(window).scrollTop(); //num of pixels hidden above current screen var docViewBottom = docViewTop + $(window).height(); var elemTop = $(elem).offset().top; //num of pixels above the elem var elemBottom = elemTop + $(elem).height(); return ((elemTop <= docViewTop)); } var catcher = $('#catcher'); var sticky = $('#sticky'); $(window).scroll(function() { if(isScrolledTo(sticky)) { sticky.css('position','fixed'); sticky.css('top','0px'); } var stopHeight = catcher.offset().top + catcher.height(); if ( stopHeight > sticky.offset().top) { sticky.css('position','absolute'); sticky.css('top',stopHeight); } }); }); </script>
The author gets it right but was too lazy to complete his tutorial on how to make the “sticky sidebar widget” stop at the footer. He left a hint on how it’s done, but I know nothing about javascript…
NOTE: If you have a tall footer on your website, then you might notice some overlap issues when you scroll all the way to the bottom of your site. You’ll have to specify the footer div as a second “catcher” and then add two more if statements to the $(window).scroll() area. I’ll let you hack around with this if you need it cause I’m feeling lazy right now… 😉
What does that mean? Any idea on what the final script should look like? I just so happen to have a tall footer, and I need the “sticky sidebar widget” to stop when it reaches the footer to avoid overlapping it. Help?
- The topic ‘Help me with this javascript (sticky sidebar widget)?’ is closed to new replies.