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).
I found a simple jQuery library called Sticky Table Headers. Two lines of code and it did exactly what I wanted. The solutions above don't manage the column widths, so if you have table cells that take up a lot of space, the resulting size of the persistent header will not match your table's width.
http://plugins.jquery.com/StickyTableHeaders/
Usage info here: https://github.com/jmosbech/StickyTableHeaders
This will help you to have a fixed header which can also be scrolled horizontally with data.
Well, I was trying to obtain the same effect without resorting to fixed size columns or having a fixed height for the entire table.
The solution I came up with is a hack. It consists of duplicating the entire table then hiding everything but the header, and making that have a fixed position.
HTML
CSS
javascript
See here: http://jsfiddle.net/QHQGF/7/
Edit: updated the code so that the thead can receive pointer events(so buttons and links in the header still work). This fixes the problem reported by luhfluh and Joe M.
New jsfiddle here: http://jsfiddle.net/cjKEx/
In this solution fixed header is created dynamically, the content and style is cloned from THEAD
all you need is two lines for example:
var $myfixedHeader = $("#Ttodo").FixedHeader(); //create fixed header $(window).scroll($myfixedHeader.moveScroll); //bind function to scroll event
My jquery plugin FixedHeader and getStyleObject provided below you can to put in the file .js
I was able to fix the problem with changing column widths. I started with Andrew's solution above (thanks so much!) and then added one little loop to set the widths of the cloned td's:
This solves the problem without having to clone the entire table and hide the body. I'm brand new to JavaScript and jQuery (and to stack overflow), so any comments are appreciated.
I have tried it using transformation:translate. While it works good in Firefox and Chrome, there is simply no function in IE11. No double scroll bars. Supports table tfoot and caption. Pure Javascript, no jQuery.
http://jsfiddle.net/wbLqzrfb/42/