Skip to content

Instantly share code, notes, and snippets.

@lawliet89
Last active January 30, 2016 01:52
Show Gist options
  • Save lawliet89/6654953 to your computer and use it in GitHub Desktop.
Save lawliet89/6654953 to your computer and use it in GitHub Desktop.
jQuery Contained Sticky Scroll
/*!
* Contained Sticky Scroll
* Adapted from Matt Ward's code
* http://blog.echoenduring.com/2010/11/15/freebie-contained-sticky-scroll-jquery-plugin/
*/
(function($){
$.fn.containedStickyScroll = function(options) {
var defaults = {
offsetTop: 0,
topClass: '',
scrollClass: '',
bottomClass: ''
}
options = $.extend(defaults, options);
var $object = $(this);
$object.addClass(options.topClass);
$(window).scroll(function() {
if (($object.parent().height() + $object.parent().position().top - 30) <
($(window).scrollTop() + $object.height())) {
$object.removeClass(options.scrollClass).removeClass(options.topClass)
.addClass(options.bottomClass);
}
else if($(window).scrollTop() < ($object.parent().offset().top)){
$object.css("top", "0px");
$object.removeClass(options.scrollClass).removeClass(options.bottomClass)
.addClass(options.topClass);
} else {
var offset = ($(window).scrollTop() - $object.parent().offset().top + options.offsetTop);
$object.css("top", offset + "px");
$object.removeClass(options.topClass).removeClass(options.bottomClass)
.addClass(options.scrollClass);
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment