Skip to content

Instantly share code, notes, and snippets.

@CoryDuncan
Last active June 29, 2017 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CoryDuncan/5365763 to your computer and use it in GitHub Desktop.
Save CoryDuncan/5365763 to your computer and use it in GitHub Desktop.
Simple jQuery plugin to emulate position: sticky
/******************************************************************************
* jQuery.fn.scrollSticky
* Applies a UI state class to an element when the user scrolls to it. Works well
* for fixed positioning UI that is dependent on scroll
*******************************************************************************/
$.fn.scrollSticky = function ( options ) {
var methods = {
init: function() {
return this.each(function ( index ) {
var $item = $( this ),
offset = $item.offset().top,
time = new Date().getTime(),
id = time + index;
// if item is already sticky, exit
if ( $item.data('isSticky') === true ) {
return false;
}
// set data id as namespace so event can be unbound without affecting other sticky events
$item
.removeData('sticky-id')
.data('sticky-id', id)
.data('isSticky', true);
// bind custom scroll event to window
$(window).bind('scroll.stickyscroll-' + id, function() {
var docScroll = $(document).scrollTop();
if ( docScroll >= offset ) {
$item.addClass('s-fixed');
} else {
$item.removeClass('s-fixed');
}
});
});
},
reset: function () {
return this.each(function () {
var $item = $(this),
id = $item.data('sticky-id');
// if sticky id is false, exit
if ( !id ) {
return false;
}
// unbind custom scroll event
$(window).unbind('scroll.stickyscroll-' + id);
// remove sticky attributes
$item
.removeData('sticky-id')
.removeData('isSticky')
.removeClass('s-fixed');
});
}
};
// if options is a valid method, execute it
if ( methods[options] ) {
return methods[options].apply( this, Array.prototype.slice.call(arguments, 1) );
}
// or, if options is a config object, or no options are passed, init
else if ( typeof options === 'object' || !options ) {
return methods.init.apply( this, arguments );
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment