Skip to content

Instantly share code, notes, and snippets.

@yuchant
Created February 26, 2012 20:55
Show Gist options
  • Save yuchant/1918945 to your computer and use it in GitHub Desktop.
Save yuchant/1918945 to your computer and use it in GitHub Desktop.
jQuery - stick element to top upon scrolling
/*
Stick element to top
Version 0.01
Usage:
$("#product_preview_container").stickyElement({ // apply to element to stick.
stopPoint: $("#products_see_more"), // integer or jquery element to stop fading at
stopPointOffset: 100, // offset the stop point
stickThreshold: 89, // when to start sticking
topOffset: 0
})
By Yuji Tomita
February 26, 2012.
*/
(function( $ ){
$.fn.stickyElement = function(options) {
defaultOptions = {
stickThreshold: 0, // height of viewport to stick from
topOffset: 0, // container top offset
containerHeight: $(this).height(),
stopPoint: null,
stopPointOffset: 0
};
if (typeof options == 'object') {
options = $.extend(defaultOptions, options);
} else {
options = defaultOptions;
};
var stickThreshold = options['stickThreshold'];
var topOffset = options['topOffset'];
var $fixedElement = this;
var heightOfContainer = $fixedElement.height();
// must stop before bar obscures all items
var stopPoint = options['stopPoint'];
if (isNaN(stopPoint)) {
stopPoint = $(stopPoint).offset().top;
};
stopPoint = stopPoint - heightOfContainer - options['stopPointOffset'];
if (! this.data('initialized')) {
// replace current element with height offsetter - but only once.
var heightContainer = $('<div/>').css('height', heightOfContainer);
this.parent().prepend(heightContainer);
this.data('initialized', true);
}
$(window).unbind('scroll').scroll(function() {
var top = $(window).scrollTop()
// stick to top until features
if (top >= stickThreshold) {
// Viewport is lower than stick threshold pixels
// -----------------------------------------------
if (top >= stopPoint) {
// viewport is lower than the stop point - stop.
$fixedElement.css({
top: stopPoint + topOffset - stickThreshold, // must subtract height of navbar
position: 'absolute'
});
} else {
// top is lower - keep at top of screen
$fixedElement.css({
top: topOffset,
position: 'fixed'
});
}
} else {
// viewport is higher than threshold - keep at wherever it's supposed to be
$fixedElement.css({
top: '0px',
position: 'absolute'
});
} // end scroll handling
}).scroll() // end scroll sticking
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment