CODE: Jquery Follow-On-Scroll Fixed Sticky Sidebar with Cutoff

I can no longer recommend this use of this script as it’s been many years and I haven’t tested it recently.

Purpose

Allows you to have an element sit in a fixed position in the window as the user scrolls.

Capabilities

  • Set the distance from the top of the window where the element is fixed.
  • Set the distance scrolled from the top of the page at which the element becomes fixed.
  • Prevents the element from pushing down the footer when the bottom of the page is reached by unfixing the element at the top of the footer.

Limitations

Does not work on mobile devices where you would not be likely to utilize a fixed element in this way.

Instructions

  • Ensure that Jquery is loading on your site. Instructions
  • Add the script below to your website’s primary script file, often ‘script.js.’
  • Enter the relevant information into the script as described in the code comments.
// Sticky Sidebar – CSS Tricks – Optimized by Doug Neiner and Julian Ware $(function() { $sticky = $(‘#sticky’), // Scrolling element $footer = $(‘footer’), // Footer container $sidebar = $(‘aside’), // Sidebar Container scrollPoint = 100, // Distance to scroll before sticking topPadding = 100, // Fixed minimum distance from top of window bottomPadding = 40, // Adjustment to scrolling element point of deactivation at footer $window = $(window), documentHeight = $(document).height(), sidebarHeight = $sidebar.outerHeight(), footerHeight = $footer.outerHeight(), offset = $sticky.offset(); $window.scroll(function() { if (($window.scrollTop() > offset.top – scrollPoint) && ($window.scrollTop() < (documentHeight – footerHeight) – sidebarHeight + bottomPadding)) { $sticky.stop().animate({marginTop: $window.scrollTop() – offset.top + topPadding},0); // Last number is drag animation duration } else { $sticky.stop().animate({marginTop: 0},0); // Input same drag animation duration as above } }); }); // End Sticky Sidebar