I am trying to design an HTML table where the header will stay at the top of the page when AND ONLY when the user scrolls it out of view. For example, the table may be 500 pixels down from the page, how do I make it so that if the user scrolls the header out of view (browser detects its no longer in the windows view somehow), it will stay put at the top? Anyone can give me a Javascript solution to this?
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>info</td>
<td>info</td>
<td>info</td>
</tr>
<tr>
<td>info</td>
<td>info</td>
<td>info</td>
</tr>
<tr>
<td>info</td>
<td>info</td>
<td>info</td>
</tr>
</tbody>
</table>
So in the above example, I want the <thead>
to scroll with the page if it goes out of view.
IMPORTANT: I am NOT looking for a solution where the <tbody>
will have a scrollbar (overflow:auto).
This is by far the best solution I've found for having a fixed table header.
UPDATE 5/11: Fixed horizontal scrolling bug as pointed out by Kerry Johnson
Codepen: https://codepen.io/josephting/pen/demELL
Well, after reviewing all available solutions I wrote plugin which can freeze any row (not only th) at the top of page or container. It's very simple and very fast. Feel free to use it. http://maslianok.github.io/stickyRows/
A bit late to the party, but here is an implementation that works with multiple tables on the same page and "jank" free (using requestAnimationFrame). Also there's no need to provide any width on the columns. Horizontal scrolling works as well.
The headers are defined in a
div
so you are free to add any markup there (like buttons), if required. This is all the HTML that is needed:https://jsfiddle.net/lloydleo/bk5pt5gs/
You would do something like this by tapping into the
scroll
event handler onwindow
, and using anothertable
with a fixed position to show the header at the top of the page.HTML:
CSS:
JavaScript:
This will show the table head when the user scrolls down far enough to hide the original table head. It will hide again when the user has scrolled the page up far enough again.
Working example: http://jsfiddle.net/andrewwhitaker/fj8wM/