Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
On large HTML tables, in a height-constricted viewport, keeps the 'thead' visible while the table is scrolled.
(function($){
$.fn.extend({
fixedTableHeader: function(options) {
var defaults = { wrapper : null, offset : 0 };
options = $.extend(defaults, options);
return this.each(function() {
var o = options;
if (o.wrapper === null) { $(this).wrap('<div class="w" />'); o.wrapper = $('.w'); }
var scrollbarWidth = function(){var a=$('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div></div>');$('body').append(a);var b=$('div',a).innerWidth();a.css('overflow-y','auto');var c=$('div',a).innerWidth();$(a).remove();return b-c;};
$(this).clone().appendTo(o.wrapper).wrap('<div class="b" />');
$(this).wrap('<div class="h" />');
$('div.h', o.wrapper).css({ 'padding-right': scrollbarWidth + 'px' });
$('div.h table', o.wrapper).css({ 'margin-right': scrollbarWidth + 'px' });
o.wrapper.css({'overflow': 'hidden'});
$('div.h').css({ 'overflow-y': 'hidden', 'height': ($('div.h thead').outerHeight() + o.offset) + 'px' });
$('div.b').css({ 'overflow-y': 'scroll', 'position': 'relative', 'height': (o.wrapper.innerHeight() - $('div.h thead').outerHeight()) + 'px' });
$('div.h table tbody, div.b table thead').css({ 'visibility': 'hidden' });
$('div.b table').css({ 'position': 'static', 'margin-top': '-' + $('div.h thead').outerHeight() + 'px' });
});
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.