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 can be achieved by using style property transform. All you have to do is wrapping your table into some div with fixed height and overflow set to auto, for example:
And then you can attach onscroll handler to it, here you have method that finds each table wrapped with
<div class="tableWrapper"></div>
:And here is working example of this in action (i have used bootstrap to make it prettier): fiddle
For those who also want to support IE and Edge, here is the snippet:
In IE and Edge scroll is a little bit laggy... but it works
Here is answer which helps me to find out this: answer
Best solution is to use this jquery plugin:
https://github.com/jmosbech/StickyTableHeaders
This plugin worked great for us and we tried a lot other solutions. We tested it in IE, Chrome and Firefox
This is my solution
I've tried most of these solutions, and eventually found (IMO) the best, modern, solution:
CSS grids
With CSS grids, you can define a 'grid', and you can finally create a nice, javascript-free, cross-browser solution for a table with a fixed header, and scrollable content. The header height can even dynamic.
CSS: Display as grid, and set the number of
template-rows
:HTML: Create a grid container and the number of defined
rows
:Here is working example:
CSS
HTML
I wrote a plugin that does this. Ive been working on it for about a year now and I think it handles all the corner cases pretty well:
Here are some demos/docs:
http://mkoryak.github.io/floatThead/
Fix your issue with this