Skip to content

Instantly share code, notes, and snippets.

@dmtintner
Forked from ewebdev/jquery.stickyHeader.js
Created February 25, 2014 13:59
Show Gist options
  • Save dmtintner/9209261 to your computer and use it in GitHub Desktop.
Save dmtintner/9209261 to your computer and use it in GitHub Desktop.
(function ($) {
$.fn.stickyHeader = function (options) {
var $window = $(window);
var settings = $.extend({}, $.fn.stickyHeader.defaults, options);
return $(this).each(function () {
var $table = $(this),
$thead = $table.children('thead'),
$navbar = $(settings.navbar),
$fixed = $('<table></table>').appendTo($thead).append($thead.clone()).addClass('fixed').css({position: 'fixed'}),
headLeftPos,
headWidth,
navbarHeight,
offsetTop,
isFixed;
var calcSizes = function () {
headLeftPos = $table.offset().left;
headWidth = $table.width();
navbarHeight = $navbar.height();
offsetTop = $thead.offset().top;
if (isFixed) {
setSizes();
}
};
var setSizes = function () {
$fixed.css($.extend(settings.getStyle(isFixed, navbarHeight), {left: headLeftPos, top: navbarHeight, width: headWidth}));
};
$window.resize(getSizes);
calcSizes();
setSizes();
$fixed.appendTo($thead);
$(window).scroll(function () {
var scrollTop = $window.scrollTop(),
shouldBeFixed = scrollTop > offsetTop - navbarHeight;
if (shouldBeFixed !== isFixed) {
$fixed.css(settings.getStyle(shouldBeFixed, navbarHeight));
isFixed = shouldBeFixed;
}
});
return this;
});
};
$.fn.stickyHeader.defaults = {
navbar: 'header',
getStyle: function (fixed, navbarHeight) {
return {transform: 'translate3d(0, ' + (fixed ? 0 : -navbarHeight) + 'px, 0)', opacity: fixed ? 1 : 0, zIndex: 1};
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment