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
You would do something like this by tapping into the scroll
event handler on window
, and using another table
with a fixed position to show the header at the top of the page.
HTML:
CSS:
#header-fixed {
position: fixed;
top: 0px; display:none;
background-color:white;
}
JavaScript:
var tableOffset = $("#table-1").offset().top;
var $header = $("#table-1 > thead").clone();
var $fixedHeader = $("#header-fixed").append($header);
$(window).bind("scroll", function() {
var offset = $(this).scrollTop();
if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
$fixedHeader.show();
}
else if (offset < tableOffset) {
$fixedHeader.hide();
}
});
This will show the table head when the user scrolls down far enough to hide the original table head. It will hide again when the user has scrolled the page up far enough again.
Working example: http://jsfiddle.net/andrewwhitaker/fj8wM/