andbamnan andbamnan - 2 years ago 182
Javascript Question

Sticky sidebar: stick to bottom when scrolling down, top when scrolling up

I have been looking for some time now for a solution to my sticky sidebar problem. I have a specific idea of how I would like it to act; effectively, I would like it to stick to the bottom as you scroll down, and then as soon as you scroll back up I would like it to stick to the top, in a fluid motion (no jumping). I am unable to find an example of what I am trying to achieve, so I have created an image that I hope will illustrate the point clearer:

Sticky sidebar: stick to bottom when scrolling down, top when scrolling up

  1. Sidebar sits under the header.

  2. As you scroll down the sidebar remains level with the content of the page so that you can scroll through both sidebar and content.

  3. Reach the bottom of the sidebar, the sidebar sticks to the bottom of the viewport (most plugins only allow for sticking to top, some that allow for sticking to bottom don't allow for both).

  4. Reach the bottom, sidebar sits above the footer.

  5. As you scroll back up, the sidebar stays level with the content so you can scroll through the content and sidebar again.

  6. Reach the top of the sidebar, the sidebar sticks to the top of the viewport.

  7. Reach the top and the sidebar sits back below the header.

I hope this is enough information. I have created a jsfiddle to test any plugins/scripts, which I have reset for this question:

Many thanks in advance if anyone has a solution for me.

Answer Source

Thanks for the great graphic. I was also looking for a solution to this challenge!

Unfortunately, the other answer posted here doesn't address requirement #5 that stipulates the ability to scroll back through the sidebar smoothly.

I created a fiddle that implements all requirements:

The core logic that needs to be implemented is:

If scrolling up OR the element is shorter than viewport Then
  Set top of element to top of viewport If scrolled above top of element
If scrolling down then
  Set bottom of element at bottom of viewport If scrolled past bottom of element

In the fiddle I use CSS3 transform for moving the target element around, so it won't work in e.g. IE<9. The logic is sound though for using a different approach.

Also, I modified your fiddle so that the sticky sidebar has a gradient background. This helps to show that the proper behavior is being exhibited.

I hope this is useful to someone!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download