Posted By

jsatt on 09/27/09


Tagged

header table jquery head heading fixed frozen non-scrolling


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

sulfurito
alejandrosuch


Fixed table header


 / Published in: jQuery
 

URL: http://jsatt.blogspot.com

Tested and working with:

  • Internet Explorer(Win) (6.0, 7.0, 8.0)

  • Firefox(Win, Linux) (3.0)

  • Safari(Win, Mac) (3.0)

  • Chrome (Win) (2.0)

  • Opera (Win) (9.6)

Tested and having issues with:

  • Firefox (All) (1.0, 1.5, 2.0)

A sample HTML layout can be seen here

Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported

  1. function scrollableTable(contain, headerClass){
  2. //default values for params
  3. //container(s) to make children adjustable
  4. var contain = contain || ".scrollContainer";
  5. //class name to apply created header(s)
  6. var headerClass = headerClass || "scrollHead";
  7.  
  8. //for each matching container
  9. $(contain).each(function(){
  10.  
  11. //remove any existing headers
  12. $(this).find('.'+headerClass).remove();
  13.  
  14. //set globals for elements to work with
  15. var container = $(this).css('position','relative');
  16. var scrollTable = container.find('table');
  17. var header = $('<table/>')
  18. .addClass(scrollTable.attr('class'))
  19. .addClass(headerClass)
  20. .append(container.find('thead').clone())
  21. .prependTo(container);
  22.  
  23. //resize and move header
  24. function adjustHeader(){
  25. header
  26. .css('position','absolute')
  27. .css('top',container.scrollTop())
  28. .css('left',(
  29. scrollTable.position().left + container.scrollLeft()
  30. )
  31. )
  32. .width(scrollTable.width())
  33. .find('th').each(function(i){
  34. $(this).width($(container.find('tbody td').get(i)).width());
  35. })
  36. }
  37.  
  38. //initial adjustment
  39. adjustHeader();
  40.  
  41. //adjust when scrolling
  42. container
  43. .unbind('scroll')
  44. .scroll(adjustHeader);
  45.  
  46. //adjust when window is resized
  47. $(window).resize(adjustHeader);
  48.  
  49. })
  50. }

Report this snippet  

You need to login to post a comment.