(Hey, first post from a longtime lurker :)
I've built a simple sidebar that does the 'absolute-to-fixed' trick to stay on screen, but would like to take in account scenarios, where the sidebar is higher than the viewport.
So I came up with this idea. It all starts as in above:
But here it gets more dynamic:
If sidebar is taller than the viewport, it continues to scroll with the content until the bottom of the sidebar is reached, and it fixes there. The top of the sidebar scrolls beyond top of viewport.
When the user scrolls back towards page top, the sidebar moves with the content until the top of the sidebar is reached, and it fixes there. The bottom of the sidebar scrolls beyond the bottom of the viewport.
This way the sidebar reacts to scrolling as usual, while sticking around close enough to find on long pages.
Any pointers to examples, or jQuery- friendly code snippets/guidelines would be much appreciated.
A sticky sidebar is a web design technique to keep the sidebar on the screen even if the user has scrolled past the position where it initially displayed.
To get the height of the scroll bar the offsetHeight of div is subtracted from the clientHeight of div. OffsetHeight = Height of an element + Scrollbar Height. ClientHeight = Height of an element. Height of scrollbar = offsetHeight – clientHeight.
In summary, scrollTop is how much it's currently scrolled, and scrollHeight is the total height, including content scrolled out of view.
I had this exact idea for a project, here's a example of how to implement it
http://jsfiddle.net/ryanmaxwell/25QaE/
The behaviour you would like to achieve is called 'affix'. Twitter's Bootstrap front-end framework has a javascript component that can do what you would like to get. Please check the section about the affix component. In fact, there you can also see a demonstration of the desired behaviour, the menu in the left sidebar is affixed.
You can define functions for the offset parameter of the affix init call, so it can be dynamically determined when to pin/unpin the element. To see an example in context, check the source of the above linked page, specifically look for application.js
, it contains the setup of the affix that you can see on the left side. Here you can see the init code taken out of context:
// side bar $('.bs-docs-sidenav').affix({ offset: { top: function () { return $window.width() <= 980 ? 290 : 210 } , bottom: 270 } })
It is probably also worth to check in the page sources the docs.css
stylesheet, which contains some positioning and styling for the affixed element. Checking this might solve your problem, or at least could give you and idea.
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