Skip to content

Instantly share code, notes, and snippets.

@sagarjadhav
Last active December 18, 2015 16:29
Show Gist options
  • Save sagarjadhav/5812113 to your computer and use it in GitHub Desktop.
Save sagarjadhav/5812113 to your computer and use it in GitHub Desktop.
The Sticky Scroll Sidebar plugin is designed to allow an element to stick to the top of the screen as page scrolls down, but without moving outside of the parent container.
/**
* Plugin for sticky scroll sidebar within content.
*/
// Utility : Object.create dosen't work all browsers.
if ( typeof Object.create !== 'function' ) {
Object.create = function( obj ) {
function F() {};
F.prototype = obj;
return new F();
};
}
(function( $, window, document, undefined ) {
var StickySidebar = {
init: function( options, elem ) {
var self = this;
self.elem = elem;
self.$elem = $( elem );
/* Update Options */
self.options = $.extend( {}, $.fn.rtStickySidebar.options, options );
/* Function */
self.StickyScroll();
},
StickyScroll: function() {
var self = this;
var $window = jQuery(window);
$window.scroll(function () {
if ($window.scrollTop() > (self.$elem.parent().offset().top) &&
(self.$elem.parent().height() + self.$elem.parent().position().top - self.options.bottomspace) > ($window.scrollTop() + self.$elem.height())) {
self.$elem.animate({
top: ($window.scrollTop() - self.$elem.parent().offset().top + self.options.topspace) + "px"
}, {
queue: self.options.queue,
easing: self.options.easing,
duration: self.options.duration
});
} else if ($window.scrollTop() < (self.$elem.parent().offset().top)) {
self.$elem.animate({
top: "0px"
}, {
queue: self.options.queue,
easing: self.options.easing,
duration: self.options.duration
});
}
});
}
};
$.fn.rtStickySidebar = function( options ) {
return this.each(function() {
var stickysidebar = Object.create( StickySidebar );
stickysidebar.init( options, this );
/* Store Data */
$.data( this, 'rtStickySidebar', stickysidebar );
});
};
$.fn.rtStickySidebar.options = {
easing: 'linear',
duration: 1000,
queue: false,
topspace: 10,
bottomspace: 10
};
})( jQuery, window, document );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment