Skip to content

Instantly share code, notes, and snippets.

@twaddington
Created March 8, 2011 02:44
Show Gist options
  • Save twaddington/859760 to your computer and use it in GitHub Desktop.
Save twaddington/859760 to your computer and use it in GitHub Desktop.
Sticks an element to the top of the window after scrolling past it.
/**
* Copyright (c) 2011 Tristan Waddington <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
**/
(function($) {
var settings, elem, offset;
$.fn.stickybox = function(options) {
if ($(this).length > 0) {
elem = $(this);
offset = elem.offset();
// Override defaults
settings = $.extend(default_settings, options);
// Update initial position in case the page loaded below the offset
update_position();
// Register scroll handler
$(document).scroll(function() {
update_position();
});
}
return $(this);
};
update_position = function() {
if ($(document).scrollTop() >= offset.top) {
elem.addClass(settings.stuck_class).css({
'display': 'block',
'position': 'fixed',
'width': '100%',
'top': 0,
'left': 0,
});
}
else {
elem.removeClass(settings.stuck_class).css({
'position': 'relative'
});
}
}
var settings;
var default_settings = {
'stuck_class': 'stickybox-stuck'
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment