I'm trying to keep a table header fixed using the Javascript scroll
event to manipulate the table header's top
property.
This technique seems to perform drastically different depending on browser and screen resolution (My primary site visitors are Retina MBP). Currently it stutters badly. It may seem to work fine in this Fiddle, but will actually be slow and janky once on your desktop.
https://jsfiddle.net/taylorpalmer/exp057a5/
I need to be able to scroll the page and have the table header stick as you scroll past it.
var allTh = document.querySelectorAll("th");
var leftCells = document.querySelectorAll(".fixed-col");
var latestKnownScrollX = 0;
var latestKnownScrollY = 0;
var ticking = false;
var onScroll = function() {
latestKnownScrollX = document.body.scrollLeft;
latestKnownScrollY = document.body.scrollTop;
requestTick();
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(update);
}
ticking = true;
}
var immediate = true;
var update = function() {
console.log('scrolling');
ticking = false;
var currentScrollY = latestKnownScrollY;
var currentScrollX = latestKnownScrollX;
var translateHead = (currentScrollY) +"px";
for(var i=0; i < allTh.length; i++ ) {
allTh[i].style.top = translateHead;
}
var translateCell = currentScrollX + "px";
for(var i=0; i < leftCells.length; i++ ) {
leftCells[i].style.left = translateCell;
}
};
window.addEventListener("scroll", onScroll);
Things I have already tried:
- Using
requestAnimationFrame()
– it's currently implemented - Debouncing scroll – didn't improve performance
- Throttling scroll - didn't improve performance
- Using
transform: translate()
instead oftop
– didn't make a difference
Things I've thought about, but won't work
- Using
position: fixed
or similar: the header cells would lose their dynamic widths and make the table worthless