I'm using this jQuery to make table headers sticky.
(function($)
{
$.fn.sticky = function()
{
var tableId = this;
var tableWidth = $(tableId).width();
var tableHeight = $(tableId).height();
var thHeight = $(tableId).find("th:first").parent().height();
var thWidthsArr = [];
$(tableId).find("th").each(function(){
thWidthsArr.push($(this).css("width"));
});
var pos = $(tableId).offset();
var thTop = pos.top + "px";
var thLeft = pos.left;
var firstRow = "tr:first-child";
var hasTHead = $(tableId).find("thead").length;
if(hasTHead) firstRow = "thead tr:first-child";
var count = 0;
$(tableId).find(firstRow + ">th").each(function(){
$(this).css("width", thWidthsArr[count]);
count++;
});
count = 0;
var lastRow = "tr:last-child";
$(tableId).find(lastRow + ">td").each(function(){
$(this).css("width", thWidthsArr[count]);
count++;
});
$(window).scroll(function(){
if($(window).scrollTop() > pos.top && $(window).scrollTop() < pos.top + tableHeight - thHeight)
{
$(tableId).find(firstRow).css("width", tableWidth+"px");
$(tableId).find(lastRow).css("width", tableWidth+"px");
$(tableId).find(firstRow).css("position", "absolute");
$(tableId).find(firstRow).css("top", ($("body")[0].scrollTop - 2) + "px");
$(tableId).find(firstRow).css("left", thLeft+ "px");
}
else
{
$(tableId).find(firstRow).css("position", "relative");
$(tableId).find(firstRow).css("top", thTop);
}
});
}
})(jQuery);
This works, but I've updated the look of my table using CSS and added border-collapse : collapse
This has resulted in the header size changing as it floats.
Anyone have any ideas how I can get the size to stay as the original header when it's floating?
I've created a fiddle here.. but for some reason it's not running.