A mobile-friendly, jQuery plugin that persists content (sidebar, nav, etc.) while scrolling.
A.K.A. sticky sidebar, persistent nav, fixed menu, etc.
Update: This can now be done with CSS
Read more about CSS position on MDN.
Recently I needed to persist a map while scrolling the page. The plugins I’ve used in the past were good, but none worked exactly how I wanted. So I decided to roll my own. Once it was built I figured it might be useful for someone else too.
tl;dr: Jump to the Github repo or view the demo:
Demo and Instructions
When I started there were several requirements I had in mind. As it progressed, several more requirements cropped up, and it quickly became a well-rounded little module, perfect for a tiny plugin.
Top Margin (setting)
At any point while scrolling the page I want some space between the content (map) and browser window. When the window hits the top of this margin, that’s the point when the div should stop scrolling and become fixed or sticky. The default value is 24px, but a custom value can be defined as well.
The content should fill its parents width, but the width of a fixed position element is relative to the windows dimensions. So the plugin finds the parents width and assigns it to the fixed elements width. If the window is resized the width is checked again and the elements width is updated.
Position on Load and Refresh
When the page loads or refreshes the sticky div will find its correct position or remain in its current position if the page was already scrolled to a lower position. The same is true if an anchor link is clicked, even from an external website.
On narrow devices I typically change columns to rows within a media query. On mobile devices, a large fixed element can cover the screen and overlap other content. So the plugin is disabled altogether when the window is narrower than the min-width setting (767px by default).
Height vs. Window Height
The other thing it needs to account for is height. If the fixed containers height and top margin is taller than the screen, then it disables the plugin and scrolls naturally with the page. Otherwise content within the container would be cutoff by the bottom of the window.
Neither of these update when the window is resized; only when the page is loaded or refreshed.
Demo and Instructions Github Repo