Hacker News new | ask | show | jobs
by CrendKing 843 days ago
You would think it's that easy to make the table heading sticky with just one `position: sticky;`, until you decide to do anything with the table content.

I have a table with sticky head. Then I decide to add a memory feature, where if user scrolls the table body, and leaves the page, I'd save the index of the first visible row, and restore the scroll position when user comes back. I noticed that every time the restored position is always about one row too downward. For instance, when I want to restore to row 5, it restores to row 6 plus a few pixels. Turns out, once I turned the thead semi-transparent, I can see row 5 was indeed at the top of the table, but the thead just overlaps on top and making it look like row 6 is the first visible row.

I told myself, no problem, I just modify the scroll position to be aware of the thead's height. It worked fine at first, but from time to from it'd still be off a few pixels. Turns out, because the table is huge, I'm doing lazy loading upon the scroll event. And because I'm using the default automatic table layout (instead of the fixed layout), sometimes certain head cell becomes too narrow and word wraps, thus increases the whole head's height. The final solution is to create a ResizeObserver[1] on the thead element and dynamically adjust the scroll position if its height changes.

[1] https://developer.mozilla.org/en-US/docs/Web/API/ResizeObser...

2 comments

Ohh, thank you very much. I was avoiding sticky headers exactly because of this problem
Or make a paginated table? This sounds like a problem made by having infiniscroll pages.
Pagination should only be used if the dataset is yoo big to be reasonably rendered as one page, as it prevents you from using Ctrl-F or sorting the table by different columns Client-Side.
Or... you do all that sorting and searching server side as well. Which... I've got mixed feelings on this, and tend to not do it unless 1) it's an absolute must and/or 2) I'm using a toolkit that already supports it. Without those, I'd tend to just throw everything down and let the client be able to do all it's sorting/filtering/etc at the client.
GP said they are lazy loading table content on scroll, so they already lost Ctrl+F and client-side sorting anyway.