Julian Ware

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

jQuery follow scroll fixed sidebar with cutoff

Purpose

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

Capabilities

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

$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)
            }
        })
    })
}
Exit mobile version