I am trying to design an HTML table where the header will stay at the top of the page when AND ONLY when the user scrolls it out of view. For example, the table may be 500
Here is a solution that builds upon the accepted answer. It corrects for: column widths, matching table style, and when the table is scrolled in a container div.
Usage
Ensure your table has a JavaSript tag because only thead content will be fixed.
$("#header-fixed").fixHeader();
//Custom JQuery Plugin
(function ($) {
$.fn.fixHeader = function () {
return this.each(function () {
var $table = $(this);
var $sp = $table.scrollParent();
var tableOffset = $table.position().top;
var $tableFixed = $("
")
.prop('class', $table.prop('class'))
.css({ position: "fixed", "table-layout": "fixed", display: "none", "margin-top": "0px" });
$table.before($tableFixed);
$tableFixed.append($table.find("thead").clone());
$sp.bind("scroll", function () {
var offset = $(this).scrollTop();
if (offset > tableOffset && $tableFixed.is(":hidden")) {
$tableFixed.show();
var p = $table.position();
var offset = $sp.offset();
//Set the left and width to match the source table and the top to match the scroll parent
$tableFixed.css({ left: p.left + "px", top: (offset ? offset.top : 0) + "px", }).width($table.width());
//Set the width of each column to match the source table
$.each($table.find('th, td'), function (i, th) {
$($tableFixed.find('th, td')[i]).width($(th).width());
});
}
else if (offset <= tableOffset && !$tableFixed.is(":hidden")) {
$tableFixed.hide();
}
});
});
};
})(jQuery);