I have used code from this SO question to successfully create fixed table headers, however I'm having a few issues adapting it to my page that I can't figure out. I'm a little new to Javascript/jQuery so please bear with me a little.
The code relies on the scroll event in the browser to detect when the
THEAD is out of view so that it knows when to clone the table and position the cloned header at the top of the page.
However my page has a DIV fixed at the top of the page that contains a search bar etc and when this is present the fixed header does not work. I'm struggling to find a way around this as I need the fixed area. It's probably really simple but I'm not seeing it.
The code snippet is as follows:
function moveScroll() {
var scroll = $(window).scrollTop();
var anchor_top = $("#maintable").offset().top;
var anchor_bottom = $("#bottom_anchor").offset().top;
if (scroll > anchor_top && scroll < anchor_bottom) {
clone_table = $("#clone");
if (clone_table.length === 0) {
clone_table = $("#maintable").clone();
clone_table.attr({
id: "clone"
}).css({
position: "fixed",
"pointer-events": "none",
top: 0
}).width($("#maintable").width());
$("#table-container").append(clone_table);
$("#clone").width($("#maintable").width());
$("#clone").css({
border: "none"
});
$("#clone thead").css({
visibility: "true"
});
$("#clone tbody").css({
visibility: "hidden"
});
var footEl = $("#clone tfoot");
if (footEl.length) {
footEl.css({
visibility: "hidden"
});
}
}
} else {
$("#clone").remove();
}
}
$(window).scroll(moveScroll);
Here's a JSFiddle with a stripped down version of the page.
If you remove the CSS sections for #topsection
and #table-container
you'll see the fixed headers in action. When these sections are present nothing works.
As an aside, I also have one other issue. If I use border-collapse:collapse
on the table to get nice borders Firefox doesn't render the fixed header properly. It renders a full empty table over the top instead. Any ideas how to circumvent this?