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

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.
  • Set a cutoff point where the element returns to it original poisiton.

Limitations

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

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 below.
  • When set up correctly, by fussing with the stickPoint and topPadding settings, the sticky element should become fixed exactly when it reaches the topPadding height. You’ll get the hang of it. 🙂
$sticky = $('#sidebar-widget')
This is where you enter the element that you want to stick on scroll. Add this element to the first line as well.

$sidebar = $('aside') 
This is the container or parent of the element you want to stick on scroll. 

stickPoint = 130 
This is how many pixels you can scroll before the element sticks.

topPadding = 160 
This is how far from the top of the window the sticky element remains as it scrolls.

cutoffPadding = 160 
This is how you set the cutoff point by adding space to the bottom in addition to the footer that should be avoided.

The two 300 in the code represent the timing of the animation for the sticky element scrolling. 1000 equals 1 second. The first one is for scrolling and the second is for the cutoff. 

Code

if ($(window).width() > 768 && $('#sidebar-widget').length) {
    $(function() {
        $sticky = $('#sidebar-widget'),  
        $sidebar = $('aside'), 
        stickPoint = 135, 
        topPadding = 162, 
        cutoffPadding = 160, 
        $window = $(window), 
        sidebarHeight = $sidebar.outerHeight(), 
        offset = $sticky.offset()
        $window.scroll(function() {
            if (($window.scrollTop() > offset.top - stickPoint) && ($window.scrollTop() < sidebarHeight - cutoffPadding)) {
                $sticky.stop().animate({
                    marginTop: $window.scrollTop() - offset.top + topPadding
                }, 300)
            } else {
                $sticky.stop().animate({
                    marginTop: 0
                }, 300)
            }
        })
    })
}