Persistant Headers on Tables
When you scroll down a page with a long table on it, typically the header of the table scrolls away and becomes useless. This code clones the table header and applies it at the top of the page once you have scrolled beyond it, and disappears when you have scrolled past the table.
function UpdateTableHeaders() {
$("div.divTableWithFloatingHeader").each(function() {
offset = $(this).offset();
scrollTop = $(window).scrollTop();
if ((scrollTop > offset.top) && (scrollTop < offset.top + $(this).height())) {
$(".tableFloatingHeader", this).css("visibility", "visible");
$(".tableFloatingHeader", this).css("top", Math.min(scrollTop - offset.top, $(this).height() - $(".tableFloatingHeader", this).height()) + "px");
}
else {
$(".tableFloatingHeader", this).css("visibility", "hidden");
$(".tableFloatingHeader", this).css("top", "0px");
}
})
}
$(document).ready(function() {
$("table.tableWithFloatingHeader").each(function() {
$(this).wrap("<div class="divTableWithFloatingHeader" style="position:relative"></div>");
$("tr:first", this).before($("tr:first", this).clone());
clonedHeaderRow = $("tr:first", this)
clonedHeaderRow.addClass("tableFloatingHeader");
clonedHeaderRow.css("position", "absolute");
clonedHeaderRow.css("top", "0px");
clonedHeaderRow.css("left", "0px");
clonedHeaderRow.css("visibility", "hidden");
});
UpdateTableHeaders();
$(window).scroll(UpdateTableHeaders);
});
Nice idea, I think it needs some improvement. It’s rather jumpy.
Does not work in IE7, too bad :(
This works fine in IE7.
Actually it doesn’t work in IE7 using IE7 Standards…
(using IE9 — Developer Tools — Browser mode: IE7, Document Mode: IE7 standards)
It clones the header, but it doesn’t persist it on the page. I am still trying to find a solution for this.
it is something which is i am looking for thank you
Laxman Parmar
The problem comes in of the table is wider than its container and horizontal scroll appears, which is very common in reports.
In this case, cloned header should be able to scroll horizontally together with the table. So far I didn’t get a proper solution to that problem.
Does this work on an iphone ?
I just took a look on my iphone, it KINDA works, not iphone slick working but still closer than most other people’s attempts i have found online so far
Awesome, it’s exactly what I was looking for.
What should I do if I have a fixed header 200px high and the content starts 200px below? How can I modify the offset for my table headers?
Thanks
This is really useful.
Nice..this gave an amazing look to my website http://www.wrangle.in
Thanks alot for that :)
Very nice.
Is there a way to persist the header inside a div with auto scroll (overflow:auto;)?
Thank you.