文章

jQuery Plugin – Stupid Fixed Header for HTML Table

Sometimes you would like to have a nice table to navigate data with the header fixed on top while scrolling. There are many Javascript dataGrid component out there to do this but sometimes you just don’t need all those features. So I have wrote a jQuery plugin to create a fixed table header on a normal HTML table. It’s called Stupid Fixed Header .

I called it ‘stupid’ because it does so many things to achieve this little effect:

  1. create extra divs to wrap table up
  2. cloning current table header
  3. put the cloned table header on top of the current table
  4. synchronize width of each cell
  5. synchronize scroll position when scrolling

This idea is not original. I have read it elsewhere but cannot find the source again. So I do it in jQuery way.

The good things:

  • supports horizontal scroll
  • work across browsers (tested on IE6/7, Firefox3.1, Opera9.5, Chrome0.2, Safari 3.1.2).

The bad things:

  • in order to calculate correct cell width in different browsers, I have made certain assumptions in the default implementation: table’s border-collapse is collapse, cell have borders, etc. Therefore, you may need to make change for the width calculation. This is made possible by supplying adjustWidth to the plugin option. (However, dealing with width in table can be really troublesome. Even current implementation is not pixel perfect.)
  • Firefox has a bug of missing border when placing table inside a overflow div. Some specific CSS rules has been added to the sample page to workaround this.
  • It’s not pixel perfect.
  • It may not perform well.
  • The header cells will not get resized when the table cells width changes. This can be done by re-calculate the cells width and add custom event to the table for triggering. I’ll leave it to someone who has interest in doing so…

To support IE6, I have worked around the z-index bug by hiding <select> component. The reason for not using iframe hack is that it will get flashy when scroll.

Feel free to check the demo and doc .

*