views:

508

answers:

4

I'm implementing a table with a fixed header using this kind of setup:

<div style="padding-right:18px"><!-- to account for the scrollbar on the other div -->
  <table id="head">
    <tr>
       <th>Col 1</th>
       <th>Col 2</th>
    </tr>
  </table>
</div>
<div style="height:400px; overflow-y:scroll">
  <table id="body">
    <tr>
       <td>Val 1a</td>
       <td>Val 2a</td>
    </tr>
    <tr>
       <td>Val 1b</td>
       <td>Val 2b - this cell is wide</td>
    </tr>
  </table>
</div>

I'm using dojo thus to make the column widths the same after the page loads:

dojo.addOnLoad(function(){
 var $bodyRow = dojo.query('#body tr')[0];
 var $headRow = dojo.query('#head tr')[0];
 dojo.forEach($bodyRow.cells, function(item, index){
  var w = item.offsetWidth;
  dojo.style($headRow.cells[index], 'width', w + "px");
 });
});

Unfortunately, although the widths are adjusting, they're not adjusting enough to line up. Anyone know why this isn't working? or a better way? Note: this must work in IE6.

+1  A: 

Have you tried setting the widths in CSS or do you need to implement column resizing and all that jazz? I'm not sure that javascript is the answer here.

Try something like:

th, td { width: 50%; } // get 2 equal width columns in both tables

PS, in the 'body' table it would be better to use <td> elements as <th> is meant for column/row headings. Also makes it easier to differentiate when you are writing your CSS.

sanchothefat
A: 

The widths are dynamic and should be rendered based on the content. For some columns, I could add a suggestion in css, but in the end, I need to adjust the sizes to what's actually been rendered in the browser.

(In the real code I am using s. I just forgot to change with I copied-and-pasted for my toy example above.)

sprugman
Does Dojo not have a plugin or existing tool for this? There's Stu Nichols attempts to look at but I think you'll have to choose either scrolling OR resizing http://www.cssplay.co.uk/menu/tablescroll.html
sanchothefat
A: 

offsetWidth gets the width of the element, padding and borders. setting the width using the element style, you are only setting the width of the element so each column will be off by the sum of all the horizontal borders and paddings of preceding columns

try this

dojo.addOnLoad(function(){
    var $bodyRow = dojo.query('#body tr')[0];
    var $headRow = dojo.query('#head tr')[0];
    dojo.forEach($bodyRow.cells, function(item, index){
            var w = dojo.style($bodyRow.cells[index], 'width');
            dojo.style($headRow.cells[index], 'width', w + "px");
    });
});

-Enrico

Enrico
I had also tried clientWidth, but I think you're on to something....
sprugman
Did the above code not work for you?
Enrico
A: 

http://home.tampabay.rr.com/bmerkey/examples/nonscroll-table-header.html

Pointed example does work in IE (and should work in Firefox), unfortunately doesn't work in Opera.

Arvo