[HTML] How do I make a <table> with scrollbars?
Edgar Reynaldo

I can't seem to come up with a way to make a table with a vertical scroll bar so that I can scroll up and down in the table without scrolling up and down in the window. Ideally , I'd like the table header , caption and row headers be fixed in place. If it's possible , I'd like to do it without javascript. Any one know how to do this?

I'm also having trouble getting the table to be a predefined width and height.
I tried it like this :

<table width=100px; height=100px>

but that just resizes the cells in the table. What am I doing wrong?

CGamesPlay

Put the table in a div that has a style of overflow: auto; and a height.

ImLeftFooted

I don't think its really possible. The next best thing is to make a separate table for the header and use Ryans trick for the inner/scrolling table.

Hm.. on second thought... maybe try this?

1<style>
2colgroup.scroller {
3 overflow: auto;
4}
5</style>
6 
7<table>
8 <tr>
9 <th>Header Blah</th>
10 <th>Header Blah</th>
11 </tr>
12 <colgroup span="2" class="scroller"></colgroup>
13 <tr>
14 <td>Data</td>
15 <td>Data</td>
16 </tr>
17</table>

You have to manually enter the number of columns in 'span'. 0 is supposed to mean 'all columns' but apparently support for it is flimsy.

Matthew Leverton

One browser (Firefox?) supports scrollable tables via:

<table>
  <thead><tr> ... </tr></thead>
  <tbody style="max-height: 400px; overflow: auto;">
    <tr> ... </tr>
  </tbody>
<table>

That would be the sensible way to support it, but you won't find any other browsers that do it.

You're best off making a JS function that splits tables into two. It's not very hard.

Timorg

I don't know if this solution is any good, or if it works in IE. I use linux, so it's not so easy to check. But here is how I would solve the problem.

http://www.timorg.net/scroll.html

1<TABLE CELLPADDING=0 CELLSPACING=0>
2<TR><TD>
3 <TABLE BORDER=1 CELLSPACING=0>
4 <TR>
5 <TD WIDTH=150>Colomn 1</TD><TD WIDTH=150>Colomn 2</TD><TD WIDTH=150>Colomn 3</TD><TD WIDTH=150>Colomn 4</TD>
6 </TR>
7 </TABLE>
8</TD></TR>
9<TR HEIGHT=100><TD>
10 <DIV style="overflow-y:scroll; width: 100%; height: 100">
11 <TABLE BORDER=1 CELLSPACING=0>
12 <TR><TD WIDTH=150>one-one</TD><TD WIDTH=150>two-one</TD><TD WIDTH=150>three-one</TD><TD WIDTH=150>four-one</TD></TR>
13 <TR><TD WIDTH=150>one-two</TD><TD WIDTH=150>two-two</TD><TD WIDTH=150>three-three</TD><TD WIDTH=150>four-four</TD></TR>
14 <TR><TD WIDTH=150>one-three</TD><TD WIDTH=150>two-three</TD><TD WIDTH=150>three-three</TD><TD WIDTH=150>four-three</TD></TR>
15 <TR><TD WIDTH=150>one-four</TD><TD WIDTH=150>two-four</TD><TD WIDTH=150>three-four</TD><TD WIDTH=150>four-four</TD></TR>
16 <TR><TD WIDTH=150>one-five</TD><TD WIDTH=150>two-five</TD><TD WIDTH=150>three-five</TD><TD WIDTH=150>four-five</TD></TR>
17 <TR><TD WIDTH=150>one-six</TD><TD WIDTH=150>two-six</TD><TD WIDTH=150>three-six</TD><TD WIDTH=150>four-six</TD></TR>
18 <TR><TD WIDTH=150>one-seven</TD><TD WIDTH=150>two-seven</TD><TD WIDTH=150>three-seven</TD><TD WIDTH=150>four-seven</TD></TR>
19 <TR><TD WIDTH=150>one-eight</TD><TD WIDTH=150>two-eight</TD><TD WIDTH=150>three-eight</TD><TD WIDTH=150>four-eight</TD></TR>
20 <TR><TD WIDTH=150>one-nine</TD><TD WIDTH=150>two-nine</TD><TD WIDTH=150>three-nine</TD><TD WIDTH=150>four-nine</TD></TR>
21 <TR><TD WIDTH=150>one-ten</TD><TD WIDTH=150>two-ten</TD><TD WIDTH=150>three-ten</TD><TD WIDTH=150>four-ten</TD></TR>
22 </TABLE>
23 </DIV>
24</TD></TR>
25</TABLE>

-Tim

Edgar Reynaldo

- CGamesPlay -
I put this in :

<div style="overflow: auto; height=50px; width=100px">(Table stuff)</div>

but it doesn't resize the table , and there are no scroll bars.

I found this site , which generates the code for you and it comes up with the same thing , enclose the table in div tags and use overflow: auto; for the div style as well , but that's not working.

<div style="overflow: scroll; height=50px; width=100px">

I changed it to overflow: scroll; and scroll bars appeared with no scroller , and the table still doesn't resize. When I resize the window , the table cells start to wrap , but I don't want that. How do I fix the table cells at their minimum width so that they don't wrap and scroll bars appear?

I found this web page , which has two scrolling tables , and it looks like it uses overflow:auto in the div tags too.

- Dustin -
Okay , I added in that style section and put in the colgroup tags like you said. It works somewhat as long as I keep the table in a div tag with a style of overflow: scroll; , however , even if I put the colgroup tag after the th table headers , it scrolls the entire table.

- Matthew -
I tried out

<tbody style="overflow: auto; max-height=100px">

and that doesn't work to bring up scroll bars. If I change it to overflow: scroll; , scroll bars come up but only a horizontal scroller when it doesn't need to be scrolled , and no vertical scroller when there's not enough space for all the rows. What did you mean by using javascript to split the table in two? I've never even used javascript before. Would it read the table and make one table with the headers and another table with the rest of the rows or what?

- Timorg -
Your html works for me in both SeaMonkey and IE7 , although it's a little strange to have to put two

<tr><td><table></table></td></tr>'s

inside another table just to get it to scroll properly. I do have one problem with it though , and that's that I want the table headers and the table rows to have the same width columns. I guess since I will know the number of columns ahead of time I can just add in a width=##% for each of the <td> tags , but I'd like them to remain a fixed size just large enough so that no lines wrap.

I still haven't figured out how to specify a fixed size for the table.

<table border=1; max-height=100px; max-width=100px>

doesn't work for some reason , and neither does putting the max width and height in the div tag.

Matthew Leverton

Half of the code you just wrote is incorrect.

Edgar Reynaldo
Stop mentally chanting html noob , and be specific about what's wrong and what isn't please. I only started learning html a few days ago.

Right now , I'm currently working off of Timorg's html code and it works to get the non table header rows to scroll , but the columns of the header row and the columns of the table rows don't match up for column widths.
Here's what I have :
sandbox3tablescroll.html
<!DOCTYPE HTML PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xlmns="http://www.w3.org/1999/xhtml">
<head>

<title>Welcome to Sandbox #3 , scrolling? tables !</title>
<meta name="keywords" content="sandbox, practice, lookheresearchengine" />

<style>
colgroup.scroller {
    overflow: scroller;
}
tbody tr td {}
</style>

<p>Scrolling tables , or are there?</p>
</head>

<body >


<table border=2;>

  <tr>
    <td>

      <table border=1;>
        <tbody>
          <tr>
            <td>Column 1</td>
            <td>Column 2</td>
            <td>Column 3</td>
            <td>Column 4</td>
            <td>Column 5</td>
          </tr>
        </tbody>
      </table>

    </td>
  </tr>

  <tr>
    <td>
             
      <div style="max-height: 100px; overflow-y: scroll;">
        <table border=1>
          <tbody>
            <tr>
              <td>Row 2 Column 1</td>
              <td>R2C2</td>
              <td>Row 2 Column 3</td>
              <td>Row 2 Column 4</td>
              <td>Row 2 Column 5</td>
            </tr>
            <tr>
              <td>Row 3 Column 1</td>
              <td>Row 3 Column 2</td>
              <td>Row 3 Column 3</td>
              <td>Row 3 Column 4</td>
              <td>Row 3 Column 5</td>
            </tr>
            <tr>
              <td>Row 4 Column 1</td>
              <td>Row 4 Column 2</td>
              <td>Row 4 Column 3</td>
              <td>Row 4 Column 4</td>
              <td>Row 4 Column 5</td>
            </tr>
            <tr>
              <td>Row 5 Column 1</td>
              <td>Row 5 Column 2</td>
              <td>Row 5 Column 3</td>
              <td>Row 5 Column 4</td>
              <td>Row 5 Column 5</td>
            </tr>
            <tr>
              <td>Row 6 Column 1</td>
              <td>Row 6 Column 2</td>
              <td>Row 6 Column 3</td>
              <td>Row 6 Column 4</td>
              <td>Row 6 Column 5</td>
            </tr>
            <tr>
              <td>Row 7 Column 1</td>
              <td>Row 7 Column 2</td>
              <td>Row 7 Column 3</td>
              <td>Row 7 Column 4</td>
              <td>Row 7 Column 5</td>
            </tr>
          </tbody>
        </table>
      </div>
                 
    </td>
  </tr>
</table>


</body>


</html>
Timorg

The issue with the header not lining up with the body is to do with you haven't set the width of the cells.

I set the widths for all the cells, so that they would all be the same, so that the lined up, where in your example you have allowed them to use them to automatically size to fit the content, and you get the results you see.

As for having the headings and the div in a table, it keeps them aligned together and in a block, I possibly could have used a <div> to keep them together. But I am table addicted, I use them for everything.

You are getting inline CSS styles with HTML. HTML has...

<TABLE WIDTH=100 HEIGHT=200>

The parameters are in the form, name, and then an equals sign, then the value.

Where CSS goes into a style tag, and uses a ':' instead of the equals sign, and the parameters are separated by a ';'.

<TABLE WIDTH=100 HEIGHT=200 STYLE="name: value; name: another_value;">

But you probably already know that as you have your <STYLE> tags done right.

-Tim

Edgar Reynaldo

Thanks for the clarification. The table now resizes properly for me.

Since I'm using your method , with two tables as the table data of 2 different table rows for the outer table , why doesn't it adjust the width of both rows (containing the two tables) to be the same though? If it was just a single table with two rows having different length text then the row widths would be adjusted to fit the longer data right?

I don't know how wide I need to make the rows , since this table is being built by a homemade C++ html file writer I am making. Maybe I could try and precalculate the maximum width by finding the longest string that will go into a cell but then how do I translate the number of characters into a pixel size? Does a 12pt font render 12 pixels wide?

Is there a way to force horizontal scrolling when the table isn't wide enough to prevent cell text wrapping?

Timorg
If both tables were 100% wide, the scrollbar takes up room, so the bottom table would be skinnier.

The outer table is only has two cells, one stacked on top of each other, the top table and bottom table are separate from each other, so they don't know how wide each others cells are. The same problem occurs with horizontal scrolling, the top table cells content (the table) has no idea of where the <DIV> has scrolled to.

I guess you could use javascript, get the values and apply them to the other parts of the text box, but that would be complicated, and I have no idea to go about that, and it might be very unresponsive.

As for calculating the width of a field of the cell widths, you could use a true type library, setup the font the page will use, and measure it. But fonts take up different amounts of pixel space depending on the screen resolution. A 10pt font on 1280x1024 takes up more pixel space than on a 1024x768 screen, so you will need a lib that can specify pixels as font size, and they need to interpret the pixels for font size in the same way as the browser, then to make it more painful, different browsers might interpret the heights differently.

on http://en.wikipedia.org/wiki/Point_(typography)
Scroll down to "Current DTP point system" to find more about the 'pt' system.

Also how large a 'pt' sized font is also dependent on the pixels per inch of the display. I think you can ignore it for this problem, cause I don't know if windowing systems (windows or linux based ones) bothers knowing about screen size. I hope someone can verify this.

Edit:

In firefox at least, you can only read the width of an object if you have set it, if you get the value and it isn't set, you get an empty string.

eg.
http://www.timorg.net/check_size.html

<HTML>
<BODY>
<TABLE BORDER=1 WIDTH=800>
<TR><TD NAME='blah'>Hello</TD></TR>
</TABLE>
<SCRIPT>
alert(document.getElementsByName('blah')[0].width);
</SCRIPT>
</BODY>
</HTML>
Edgar Reynaldo

Okay , found an easier way.

<style>
td {width: (maxchar*14);font-size: 14px;}
</style>

'maxchar*14' will be replaced by the actual number when the html file gets written.

However , I still can't manage to make the table cells stop wrapping text when the table isn't wide enough. Is there a min-width property? Will that force the table to make a horizontal scrollbar if there is not enough room for the table? I don't mind if the window has to scroll , but I don't want the text to wrap. It looks bad and makes it harder to read.

Timorg

If you use &nbsp; instead of a space character, the text wont be broken onto a new line.

'&nbsp;' stands for Non Breaking Space.

As for multiplying the number of characters by the px size, probably doesn't give you the width of the string, I am pretty sure the px is the height not the width of a character. But if you pick a high enough value for the character width, it will probably have the result you want.

Mordredd

I do not know much about HTML, but what about using frames? Would not this force the table to be scrollable?

Edgar Reynaldo

I used &nbsp; and it works wonderfully. Now when I set the width and height of the outer table , when it's too small a horizontal scroll bar appears. Nice!

Is there a way to set a text property so that in certain elements , all spaces are interpreted as non-breaking spaces without having to parse them in as such?

I don't know much about frames. I'll take a look at using one tomorrow , thanks for the suggestion Jacob.

Does anyone have any ideas how I can get the vertical scroll bar set outside the visible columns of the table so that the header columns and the row columns line up? I still have to set the <td> width to an approximate value so that the columns will line up nicely between the two rows of the outer table. After I figure that out should I try to set the width of the two inner tables or should I try to set the width of the two outer rows where the second one is wider by 20 pixels or so?

Matthew Leverton

You should be using JavaScript like I originally suggested. All the other solutions have drawbacks. Sometimes you can live with them, but usually not.

Regarding your incorrect HTML, you didn't even copy/paste the examples correctly. So if you want to see what you are doing wrong, you should compare your snippets with the ones other people have provided. The biggest problem is that you are mixing HTML and CSS syntax up.

<table width="500" style="width: 500px;">

The HTML width has no units. It's just a number (or a percentage). CSS uses colon and semicolon separated values.

And the accepted style of modern day HTML is to lower case everything, to use quotes around all attributes, and to close all tags.

Fladimir da Gorf

Td elements have a nowrap attribute IIRC.

Edgar Reynaldo
I don't know any javascript. Know any links to well-written tutorials/references?
Timorg helped correct me on my usage errors , and I'm cleaning them up. I'm sticking to writing style rules in the head section for the different tags for now. Thanks for the grammar tips. I retried the tips that you and Dustin provided but both failed according to the explanation I gave before. The method I'm using now encloses a normal table in two sets of div tags.

I still haven't been able to reliably set the width of a th or td cell.

I tried using a different approach , using method #1 from CSS Play - CSS scrolling tables [cssplay.co.uk] , and even though I copied the styles explicitly and used the same attributes for the different table tags , I can't get the columns of the header and the rows to synchronize widths without using position:relative; in the .outerdiv thead tr style definition but then the scroll bar moves the headers up and down as well as the tbody rows. I can't seem to get a strict cell width set for <td> and <th> tags. It adjusts the cell widths somewhat , but not to a fixed width.

Here's the html code I am using right now :
sandbox6tablescroll-cssplayA.html
<!DOCTYPE HTML PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xlmns="http://www.w3.org/1999/xhtml">
<head>

<title>Welcome to Sandbox #6 , tables scrolling yet? !</title>
<meta name="keywords" content="sandbox, practice, lookheresearchengine" />


<style>
.outerdiv {
  position:relative;
  padding:4em 0 3em 0;
  width:54em;
  background:#eee;
  margin:0 auto 3em auto;
}
.innerdiv {
  overflow:auto;
  width:54em;
  height:5em;
  background:#eee;
}
.outerdiv table caption {
  position:absolute;
  width:51.7em;
  text-align:center;
  top:0;
  left:0;
  height:1.5em;
  background:#697210;
  border:0.1em solid #fff;
  color:#fff;
}
.outerdiv thead tr {
  position:absolute;
  top:1.5em;
  height:1.5em;
  left:0;
}
.outerdiv tfoot td {
  position:absolute;
  width:51.5em;
  text-align:center;
  background:#f0c992; 
  border:0.1em solid #000;
  color:#000;
  bottom:0;
  left:0
}
.outerdiv th , outerdiv td {
  width:10em; 
  text-align:left;
}
.outerdiv th {
  background:#724a10; 
  color:#fff;}
  .outer .dk {background:#fff;
}

</style>

<p>Scrolling tables , or are there?</p>
<hr style="width:100%; height:10px; color:green; background-color:green;"/>
</head>

<body >

<div class="outerdiv">
  <div class="innerdiv">
    <table summary="Trying to make the table look nice , work with me here">
                     
      <caption>Sample table to test scroll abilities</caption>
                  
      <thead>
        <tr>
          <th scope="col">Column 1</th>
          <th scope="col">Column 2</th>
          <th scope="col">Column 3</th>
          <th scope="col">Column 4</th>
          <th scope="col">Column 5</th>
        </tr>
      </thead>
                
      <tfoot>
        <tr>
          <td colspan="5">Are the scroll bars working?</td>
        </tr>
      </tfoot>
                   
      <tbody>
        <tr class="dk">
          <th scope="row">Row 2 Column 1</th>
          <td>R2C2</td>
          <td>Row 2 Column 3</td>
          <td>Row 2 Column 4</td>
          <td>Row 2 Column 5</td>
        </tr>
        <tr>
          <th scope="row">Row 3 Column 1</th>
          <td>Row 3 Column 2</td>
          <td>Row 3 Column 3</td>
          <td>Row''3''Column''4</td>
          <td>Row 3 Column 5</td>
        </tr>
        <tr class="dk">
          <th scope="row">Row 4 Column 1</th>
          <td>Row 4 Column 2</td>
          <td>Row 4 Column 3</td>
          <td>Row 4 Column 4</td>
          <td>Row 4 Column 5</td>
        </tr>
        <tr>
          <th scope="row">Row 5 Column 1</th>
          <td>Row 5 Column 2</td>
          <td>Row 5 Column 3</td>
          <td>Row 5 Column 4</td>
          <td>Row 5 Column 5</td>
        </tr>
        <tr class="dk">
          <th scope="row">Row 6 Column 1</th>
          <td>Row 6 Column 2</td>
          <td>Row 6 Column 3</td>
          <td>Row 6 Column 4</td>
          <td>Row 6 Column 5</td>
        </tr>
        <tr>
          <th scope="row">Row 7 Column 1</th>
          <td>Row 7 Column 2</td>
          <td>Row 7 Column 3</td>
          <td>Row 7 Column 4</td>
          <td>Row 7 Column 5</td>
        </tr>
                    
      </tbody>
                  
    </table>
  </div>
</div>

</body>


</html>
Even if I adjust the width in the
.outerdiv th , .outerdiv td {
  width:10em;
  text-align:left;
}
section , it doesn't adjust all the cell widths to the same amounts.

Well , I just tried this last version in IE7 and it renders everything with the column widths adjusted to the same amount for all the rows. It doesn't render them exactly according to the width suggested , but it does a lot better than Mozilla's doing right now. How's FireFox look? I don't have it on this machine yet.

Do you see any errors in the html I'm using? I can't see any styles or attributes that I left out for any of the tags that I used. I checked over the two css files linked to in the source for the CSSplay scroller page and nothing there would affect any of the tags in what I used as far as I know. I don't understand why the CSSplay scrolling tables page renders both tables perfectly but it won't render this one right when I'm using the exact same style rules and data structure?

Any other suggestions?

- Fladimir -
How would I use the no wrap attribute? Would it work for th tags as well?
<style>
td {wrap:none; word-wrap;no ; ??:??;}
</style>
- Append -
I tried altering the dtd to match what the website was using , but it didn't fix or change anything. I was using XHTML 1.0 Transitional and the web page was using Strict. No change though.

- Append 2 -
I noticed that if all of the table row's first column tags are <td> and not <th> that then their widths don't match up with the first thead column. As soon as one is changed to use the <th> tag then it adjust the width of the cells in that column to match the header (or itself maybe). What attribute does the <th> tag have that the <td> one doesn't? The only difference in style attributes is that the <th> tag has some color attributes associated with it. Why would that matter? Is it just some intrinsic property of the <th> tag?
ImLeftFooted

I went ahead and uploaded an idea I had. Apparently its only IE5+ but it seems ideal.

http://dustytech.com/examples/scrollytable.php

I can't get rid of the horizontal scroll-bar on FF. The page is wiki-editable so if someone else has a solution please update it.

Fladimir da Gorf

In HTML: <td nowrap></td>
In XHTML: <td nowrap="nowrap"></td>

Though I'm not sure if it's in strict XHTML.

Matthew Leverton
Quote:

I went ahead and uploaded an idea I had. Apparently its only IE5+ but it seems ideal.

It looks like the same thing I suggested... But I don't think anything except Firefox supports that. I know IE7 doesn't.

And even on Firefox, the scrollbars are inside the table (which is reasonable) but the headers don't know that (which is unreasonable) so you get horizontal scrollbars.

Edgar Reynaldo

- Fladimir -
Nice , I added in the nowrap:nowrap; attribute , and now all the table row columns are lining up well. However , size changes still don't seem to affect the <thead><tr><th> column titles to the same degree as the <tbody><tr><td> cells.

.outerdiv th , .outerdiv td {
  nowrap:nowrap;
  width:250px; 
  text-align:left;
}

I also fixed a missing . dot class prefix before the outerdiv td in there.
Tweaking outerdiv , innerdiv , caption , and footer widths makes it nicer , but I still don't know how to make the column widths be a fixed non-negotiable value.

Other than that html code is same as before and now produces this (using XHTML 1.0 Transitional) :
sandbox6tablescroll-cssplayA.html
{"name":"594314","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/6\/2\/6248a699e023a49faff4f4e76496a97e.jpg","w":867,"h":472,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/6\/2\/6248a699e023a49faff4f4e76496a97e"}594314

So it only looks nice when the column widths for <th> and <td> are tweaked along with making the outer and inner div style attributes wide enough for all the columns. If there's not enough room in the div for all the columns then they get smushed together regardless of having the nowrap:nowrap; attribute for cells set.

Something else strange is that when I make the <thead><tr> tags use position:relative; instead of absolute that then the header row moves inside the inner div out of the outer div. After that the column widths auto adjust but then the headers and table rows scroll together though.

- Dustin -
Looking pretty good on the wiki , I copied out the code and made an html file out of it and it's working pretty well on SeaMonkey. It's sure a lot nicer looking than a bunch of <div> wrappers and massive styling code. I must have had too much extra junk in my html file when I tried you and Matthew's solutions last time. I took out the style attributes in the <tbody> tag and tried out the <colgroup span="2" class="scroller"></colgroup> again but I couldn't get any variation of colgroup to implement a scroller. I can't seem to get rid of the horizontal scroll bar on the wiki code either.

Yeah , IE7 doesn't like the wiki version. It makes it all huge with no scrollbars.

BAF

Seamonkey is the ugliest piece of shit ever. Looks too much like Netscape.

Edgar Reynaldo
And Firefox is soooo special.
I'll ignore the SeaMonkey comment as now I don't have to add this onto the end of my last post. - Edit - Besides , that was the classic look for Mozilla , I just hadn't set my theme to Modern yet. :P
Modern theme screenpic below.


I googled around and I found a better solution for preventing line wrapping in data cells. Use <nobr></nobr> tags around the div or table. As long as it has the overflow attribute set to auto or scroll the cells will stay in the boundaries of the table and scroll bars will appear. I also found this style attribute , but haven't tested it : style="white-space:nowrap;". I haven't found a solution to the problem of including the headers and rows in the same div or table without making the header row get scrolled as well. The best solution I've found so far is to set the width's of the <thead><tr> tag to the same width as the <tbody> - 1em for the scrollbar. Even then , if you don't set the width of the header row to the combined width of the table row's cells then you get a horizontal scrollbar and it goes out of sync with the headers. This shouldn't be so complicated.

Quote:
Put the table in a div that has a style of overflow: auto; and a height.
Check.
Quote:
The next best thing is to make a separate table for the header and use Ryans trick for the inner/scrolling table.
Check.
Quote:
You're best off making a JS function that splits tables into two. It's not very hard.
Off to learn Javascript.

Basically I started over with a fresh table , split it into two tables , one for the headers and one for the rows of the table body , with each table in its own div and a div wrapper for it all to make the background look a little better. Used <nobr> tags around the two tables and overflow:auto; in the div for the table body. Manually adjusting the widths of the components is obnoxious though and that's where the javascript should finish the job by setting the appropriate widths of the header row , and the div for the table body. It looks good in SeaMonkey and in IE7 the table rows aren't quite as wide for some reason but looks decent anyway.

Here's the latest incarnation of the scroll table :
NobrDivScrollTable.html
<!DOCTYPE HTML PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xlmns="http://www.w3.org/1999/xhtml">
<head>

<title>Nobr Div Scroll Table - Welcome to Sandbox #2 !</title>
<meta name="keywords" content="sandbox, practice, lookheresearchengine" />

<style>
.theaderdiv {
  position:relative;
  width:41.7em;
  border:3px solid cyan;
  background:#eee;
  height=1.5em;
  margin:2em 2em auto 2em;
}
.tbodydiv {
  position:relative;
  overflow:auto;
  width:42.7em;
  border:3px solid cyan;
  background:#eee;
  height:10em;
  margin:auto 2em 2em 2em;
}
.tbackgrounddiv {
  position:relative;
  width:47em;
  background:#990099;
  border:5px #663399 solid;
}
thead {
}
tbody {
}
.centered {
  text-align:center;
}
th , td {
  border:1px black solid;
  width:30em;
}
</style>

<p>Making scrolling tables using nobr , div , and overflow</p>
</head>

<nobr>

<div class="tbackgrounddiv">

<div class="theaderdiv">
<table style="cellpadding:4; cellspacing:4; border:1 solid black;">
 <thead>
  <tr>
   <th>Header Blah</th>
   <th>Header Blah</th>
  </tr>
 </thead>
</table>
</div>

<div class="tbodydiv">

<table style="cellpadding:4; cellspacing:4; border:1 solid black; width:40em;">
 <tbody>
  <tr>
   <td>Data Data Data Data Data Data Data Data Data Data</td>
   <td class="centered">DataDataDataDataDataDataDataDataDataData</td>
  </tr>
  <tr>
   <td>DataDataDataDataDataDataDataDataDataData</td>
   <td class="centered">DataDataData</td>
  </tr>
  <tr>
   <td>Data</td>
   <td class="centered">DataDataDataDataDataDataDataDataDataData</td>
  </tr>
  <tr>
   <td>DataDataDataDataDataDataDataDataDataData</td>
   <td class="centered">Data Data Data Data Data Data Data Data Data Data</td>
  </tr>
  <tr>
   <td>DataDataDataDataDataDataDataDataDataData</td>
   <td class="centered">DataDataDataDataDataDataDataDataDataData</td>
  </tr>
  <tr>
   <td>DataDataDataDataDataDataDataDataDataData</td>
   <td class="centered">DataDataData</td>
  </tr>
  <tr>
   <td>Data</td>
   <td class="centered">DataDataDataDataDataDataDataDataDataData</td>
  </tr>
  <tr>
   <td>DataDataDataDataDataDataDataDataDataData</td>
   <td class="centered">DataDataDataDataDataDataDataDataDataData</td>
  </tr>
  <tr>
   <td>DataDataDataDataDataDataDataDataDataData</td>
   <td class="centered">DataDataDataDataDataDataDataDataDataData</td>
  </tr>
  <tr>
   <td>DataDataDataDataDataDataDataDataDataData</td>
   <td class="centered">DataDataDataDataDataDataDataDataDataData</td>
  </tr>
  <tr>
   <td>DataDataDataDataDataDataDataDataDataData</td>
   <td class="centered">DataDataData</td>
  </tr>
  <tr>
   <td>Data</td>
   <td class="centered">DataDataDataDataDataDataDataDataDataData</td>
  </tr>
 </tbody>
</table>

</div>

</div>

</nobr>

</body>


</html>
And a nice little picture of the table in SeaMonkey for BAF.
jpg;820;519;160;101

Anyone care to give me a brief introduction how to interface javascript functions with html objects?
BAF

It's a little better, but I still hate seamonkey. I tried it out and went back to FF.

And I've been running FF3b2 exclusively since I installed Vista. More memory bugs fixed, their new garbage collector works quite well. Plus it doesn't slowly degrade until having to be restarted. I've had it open with quite a few tabs for... at least a week and it's locked pretty much at 265MB (doesn't go up or down much unless I open/close tabs).

CGamesPlay
Quote:

It's a little better, but I still hate seamonkey. I tried it out and went back to FF.

Stop derailing the thread.

Quote:

Off to learn Javascript.

Great! While you're at it, look at HTML, too. You have a <p> element in your <head> element, you don't provide a type attribute on your <style> element, you're using a <meta> keywords (which everyone knows search engines don't use), and you don't have a <body> element.

Instead of <nobr>, you can use CSS, as well.

As far as the actual table is concerned: I'd add an extra table header cell the size of the scroll bar, to keep the table a box.

Edgar Reynaldo

- CGamesPlay -
Like I said earlier , I only started learning html a few days ago.
The <p> element in the html header section was a leftover from a test page I was using. If a <p> element is illegal in the header then why would the browser render it any way? That's like my compiler letting me use a function I haven't defined. It shouldn't be rendered in quirks mode due to the !DOCTYPE declaration , so I blame it on the browser. :P I won't use it that way anymore. As far as not providing a type attribute on the <style> element , what do you mean? Please provide an example.

So are there really no search engines that use meta keywords anymore , or is it just Google that doesn't use them now?

As for not using a <body> element , that's due to cut-paste coding and poor oversight. If I had started a new page over , I would have put it in.

Quote:

Instead of <nobr>, you can use CSS, as well.

What CSS would I use though?
I haven't tried this yet :

<style>
table {
  whitespace:no-wrap;
}
</style>

What I'm really interested in now is figuring out how to set different element widths using javascript. Should I use an onload attribute to call a javascript function? How do I get different objects properties and use them in a function?

Remember , I'm just a beginner at all this , so be patient and specific please.

Matthew Leverton

<style type="text/css>
</style>

Quote:

What I'm really interested in now is figuring out how to set different element widths using javascript. Should I use an onload attribute to call a javascript function? How do I get different objects properties and use them in a function?

You could use an onload to call a function that scans the HTML for all tables with a certain class (say splitTable) and then does its magic.

foo.getElementsByTagName("TD") and foo.childNodes are your friends.

foo can be something like 'document' or any element.

foo.offsetWidth will give you the width of an element. Note that CSS is a bit unfriendly and you'll have to subtract the padding and border from it.

tdHeader.width = tdBody.offsetWidth - (border + padding)

Edgar Reynaldo

This javascript resizing is not going nicely.

So far I've been trying to use something like this :

<script type="text/javascript">
function AlterWidth() {
  var tableheaderdiv = document.getElementById("tableheaderdiv_id");
  alert(tableheaderdiv.width);
  tableheaderdiv.width = 400px;
  var tableheaderdiv_a = document.getElementById("tableheaderdiv_id");
  alert(tableheaderdiv_a.width);
}
</script>

// table stuff

<button onclick=AlterWidth();>Alter Table Header Div Width</button>

I've also tried that to adjust the table <head> width which does nothing in SeaMonkey , but works in IE7.

In both cases , the first alert shows up blank or says "undefined".
The second alert shows whatever width I set it to though , whether it rendered on the page or not.

The best javascript reference guide I've found so far is w3schools Javascript Reference but it doesn't have a listing of properties for the <div> tag on its HTML DOM reference. I looked at the properties for a table and it doesn't even have a height property! Sometimes I wonder just who was in charge of defining a table in HTML anyway. I'll have to do some specialized javascript testing tomorrow for <div> , <table> , <head> , and <body> to see what I can really adjust or not.

Any suggestions?

CGamesPlay
Quote:

Like I said earlier , I only started learning html a few days ago.

No, I didn't mean that with any degree of sarcasm. I was just letting you know what you needed to work on :)

Quote:

If a <p> element is illegal in the header then why would the browser render it any way? That's like my compiler letting me use a function I haven't defined. It shouldn't be rendered in quirks mode due to the !DOCTYPE declaration , so I blame it on the browser. :P

If you want, you can rename the file to .xml, and make it well-formed XHTML. The browser (Firefox has this feature, at least), will error if you have any semantic problems.

Quote:

tableheaderdiv.width = 400px;

That's not valid Javascript any more than it's valid C++ :) You need to put it in a string. For example, these work:

width = "400px";
width = 400 + "px";

Quote:

<button onclick=AlterWidth();>Alter Table Header Div Width</button>

That's not valid XML. You need attribute quotes.
<button onclick="AlterWidth();">Alter Table Header Div Width</button>

Quote:

Any suggestions?

Get Firebug. Using the HTML tab, select an element. In the right pane, select DOM. It lists all the methods and properties for the given node.

bamccaig

/derail

CGamesPlay said:

That's not valid Javascript any more than it's valid C++ :) You need to put it in a string. For example, these work:

width = "400px";
width = 400 + "px";

IMO, they should just use a single unit of measure and give you conversion functions. I know I would prefer it. I still think of strings as messy.

width = 400; // 400px
width = percentToPixels(50); // 50%.
width = emToPixels(16, fontFamily); // 16em

I think it might make positioning things easier as well if everything had a defined width, height, and position in pixels... Stupid Web languages... ::)

CGamesPlay

Then use prototype, or Ext…

bamccaig
CGamesPlay said:

Then use prototype, or Ext…

If I ever get around to doing some Web development at home I probably will, but since I know little or nothing about those right now it's not an option to just start using them at work where I do most of my Web development...

CGamesPlay

I thought so too. Then I tried out Ext, and when I converted my application to it, I had half the code size :)

bamccaig
CGamesPlay said:

I thought so too. Then I tried out Ext, and when I converted my application to it, I had half the code size :)

The problem is integrating it into the existing system. I'm also not sure about the licensing issues... :-/ It's another LGPL project (the same as that drag 'n drop library I found a while ago), though there are commercial and OEM licensing options... I would definitely like to use it though.

CGamesPlay

[TINLA] As far as licensing goes, Ext is LGPL, meaning you can use Ext in an application and doing so does not make it LGPL itself. Additionally, if you modify Ext itself, you only have to distribute the sources to the changes you make if you distribute the application. In the web world, source and application are often equivalent anyways, so LGPL is even less binding.

Edgar Reynaldo

- CGamesPlay -
Thanks for the continuing grammar and usage corrections. Let's see if I've got style usage down now.

1<!--Using an external style sheet-->
2<head>
3 <link rel="stylesheet" type="text/css" href="externalstyle.css" />
4</head>
5<!--externalstyle.css-->
6tagname {attribute:value; attribute:value;}
7 
8<!--Using an inline style sheet-->
9<head>
10<style type="text/css">
11 tagname {
12 attribute:value;
13 attribute:value;
14 }
15</style>
16</head>
17 
18<!--Using inline styles in tags-->
19<tagname style="attribute:value; attribute:value;"></tagname>

And for plain html attributes :

<tagname attribute="value" attribute="value"></tagname>

I did all but the first from memory. I think those are right.

Okay , now I have a question about defining classes. How do I properly define a subclass using <style> tags?
I tried it like this :

<style type="text/css">
.baseclass1 {
  attribute:name;
  .b1subclass1 {
    attribute:name;
  }
}
</style>

but b1subclass1 doesn't get recognized. I'd like to use some form of inheritance so that I can just use

<tagname class="b1subclass1"></tagname>

Can an element have more than one class? If they can , the second one should override the first right?

Another question , what's the best way for mousedrag resizing? Add an extra element for a grab bar and recalculate the inner element's width based on the grab bar's position?

ImLeftFooted
<tagname class="class1 class2 class3"></tagname>

Now tagname above has 3 classes associated with it. I have no clue on what order or precedence it gets.

Matthew Leverton
Quote:

I have no clue on what order or precedence it gets.

If I remember correctly, it goes based on the order the class is defined in the CSS. The order inside the attribute is irrelevant.

So if you do this:

.classname1
{
}
.classname2
{
}

Then <div class="classname1 classname2"> and <div class="classname2 classname1"> are identical with classname2 always overriding the classname1 since it comes after in the CSS file.

You can also do this:

.classname1.classname2
{
}

And that would only apply if both are present at the same time.

CGamesPlay
Quote:

I think those are right.

Yes, they all are :)

Quote:

If I remember correctly, it goes based on the order the class is defined in the CSS.

The rules for cascading are complex. First and foremost, a rule with !important always overrides other rules. Then, the rule that is more specific wins, and finally the rule that appears last in the file wins, if all else is a tie. To find out how specific a rule is, it's mostly intuitive. However, a technical explanation is available here.

Quote:

<div class="classname1 classname2"> and <div class="classname2 classname1"> are identical with classname2 always overriding the classname1 since it comes after in the CSS file.

These two are always identical, regardless of the above rules. If you want the second one to override the first, you have to either be more specific in the rule, or put it after the first.

Quote:

Another question , what's the best way for mousedrag resizing? Add an extra element for a grab bar and recalculate the inner element's width based on the grab bar's position?

Yeah, mainly. You may want to look into Ext, as it will greatly simplify your work load.

bamccaig
Edgar Reynaldo said:

Okay , now I have a question about defining classes. How do I properly define a subclass using <style> tags?
I tried it like this :

<style type="text/css">
.baseclass1 {
attribute:name;
.b1subclass1 {
attribute:name;
}
}
</style>

but b1subclass1 doesn't get recognized. I'd like to use some form of inheritance so that I can just use

<tagname class="b1subclass1"></tagname>

AFAIK, there is no such thing as sub-classes in css. Unfortunately, you're forced to define a whole new class. AFAIK.

CGamesPlay
Quote:

AFAIK, there is no such thing as sub-classes in css. Unfortunately, you're forced to define a whole new class. AFAIK.

You know correctly. However, as has been stated:

1<style type="text/css">
2.message {
3 background: #eee;
4 border: solid 1px #666;
5}
6 
7/* This rule will only affect elements with both classes. Note that
8there is no space between the class names. Adding a space has a
9different meaning. */
10.message.error {
11 background: #fee;
12 color: red;
13 font-weight: bold;
14}
15</style>
16 
17<div class="message">This is a message.</div>
18 
19<div class="message error">This is an error.</div>

The first message will appear in a gray box with a dark gray border. The second message will appear in a pink (#fee) box with a dark gray border, and with red text. Notice how the second one had all the properties of the first, but some were overridden, and new ones were added.

Edgar Reynaldo

Here's my work in progress javascript and html for converting a normal table contained inside a div into two <div><table>'s with the second being scrollable and containing the <tbody> data from the original table.

I'm having trouble with it though , perhaps the way I'm working with strings is incorrect , however , I used the same method earlier in the script and it works fine.

For some reason , there is an exception thrown at the line where I first try to assign the var newtablehtml a value using string addition. It's near the bottom of the SplitTable() function.
<code>
<!DOCTYPE HTML PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Java Script Table Adjustment</title>

<script type="text/javascript">
function SplitTable () {
var table1div=document.getElementById("table1");
var starttable=table1div.getElementsByTagName("table");
var tabletheadstring = "cellspacing=\"0\" class=\"theadtable\"";
var tabletbodystring = "cellspacing=\"0\" class=\"tbodytable\"";
var max_cell_width = 0;
for (var i = 0 ; i < 1 ; i++ ) {
//alert("Table #" + i);
var tablethtags = starttable<i>.getElementsByTagName("th");
for (var k = 0 ; k < tablethtags.length ; k++) {
if (max_cell_width < tablethtags[k].offsetWidth) {max_cell_width = tablethtags[k].offsetWidth;}
}
var tabletdtags = starttable<i>.getElementsByTagName("td");
for (var k = 0 ; k < tabletdtags.length ; k++) {
if (max_cell_width < tabletdtags[k].offsetWidth) {max_cell_width = tabletdtags[k].offsetWidth;}
}
var status_string = "";
for (var k = 0 ; k < tablethtags.length ; k++) {
status_string = status_string + "Setting the width of table th tag #" + k + " , Max Cell Width = " + max_cell_width + "\n\r";
tablethtags[k].width = max_cell_width;
}
//alert(status_string);
status_string = "";
for (var k = 0 ; k < tabletdtags.length ; k++) {
tabletdtags[k].width = max_cell_width;
status_string = status_string + "Setting the width of table th tag #" + k + " , Max Cell Width = " + max_cell_width + "\n\r";
}
//alert(status_string);
status_string = "";
var headers = starttable<i>.getElementsByTagName("thead");
alert("var headers ok");
var tablebodys = starttable<i>.getElementsByTagName("tbody");
alert("var tablebodys ok");
var newtablehtml = "";
alert("newtablehtml clear ok");
newtablehtml = newtablehtml + "<div class=\"headertablediv\">\n\r<table " + tableheadstring + ">\n\r";
alert("1");
newtablehtml = newtablehtml + " <thead>\n\r" + headers[0].innerHTML + "\n\r </thead>\n\r</table>\n\r</div>\n\r";
alert("2");
newtablehtml = newtablehtml + "<div class=\"bodytablediv\">\n\r<table " + tabletbodystring + ">\n\r";
alert("3");
newtablehtml = newtablehtml + " <tbody>\n\r" + tablebodys[0].innerHTML + "</tbody>\n\r</table>\n\r</div>\n\r";
alert(newtablehtml);
table1div.innerHTML = newtablehtml;
// table1div.innerHTML = "<table " + tabletheadstring + ">\n\r <head>\n\r" + headers<i>.innerHTML + "</head>\n\r</table>\n\r" + "<table " + tabletbodystring + ">\n\r <head>\n\r" + tablebodys<i>.innerHTML + "</head>\n\r</table>\n\r";
}

}
</script>

<style type="text/css">
.widthadjuster {
}
.heightadjuster {

}
.theadtable {
position:fixed;
border:3px #ff9900 solid;
margin:2em 2em 0em 2em;
}
.tbodytable {
top:4em;
border:3px #ff9900 solid;
margin:0em 2em 0em 2em;
}
.tablebase {
width:90%;
border:3px #ff9900 solid;
margin:2em 2em 2em 2em;
}
th , tr , td {
border:1px black solid;
}
#table1 {
}
div {
background-color:#993399;
}
.outerdiv {

}
.headertablediv {

}
.bodytablediv {
overflow:auto;
height:5em;
}
</style>
</head>

<body style="background-color:#FFCCFF;">

Working with javascript to change the layout and properties of an html table

<hr style="width:100%; height:5px; color:#006600; background-color:#006600;" />

<div id="table1">
<table cellpadding="2" cellspacing="0" class="tablebase">
Header CellHeader CellHeader CellHeader Cell
Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell Row HeaderData CellData CellData Cell
</table>
</div>

<br />
<button style="align:center;" onclick="SplitTable()">Press this button to split the table above into two tables below</button>
<br />

<div id="splitscrolltable">

</div>

</body>

</html>

</code>

I had already used a string var in that manner before with success though , and I don't see what is different that would cause it to fail.

var mystring = "";
mystring = mystring + "Javascript is weird , man";
alert(mystring);

There's nothing wrong with javascript like that is there?

bamccaig

JavaScript has the += operator, which also works for string concatenation. ;) Probably not the problem though. I'm not sure why you're concatenating \n\r to your strings. A \n should suffice... Probably still isn't the problem though.

** EDIT **

The error that I get is: "tableheadstring is not defined."

Edgar Reynaldo said:

// ...

newtablehtml = newtablehtml + "<div class=\"headertablediv\">\n\r<table " + tableheadstring + ">\n\r";

// ...

Perhaps you meant tabletheadstring? How are you debugging this? Firefox's Firebug extension told me exactly where and what the error was so if you're not using it you should be. ;)

Edgar Reynaldo

Stupid typos.
I tried using SeaMonkey's javascript debugger Venkman , but I don't know how to use it very well and when I closed Venkman , SeaMonkey locked up. Every time I tried to click on the page or open or close it , it just beeped at me. Beep. Beep. Argh!
I've got FireFox and Firebug installed now , I'll use them next time. Thanks for spotting my mistake.

- Update -
Firefox's error console (menu->tools->error console) is quite handy for catching typographical errors. SeaMonkey has one too (menu->tools->web development->error console).

The most effective method I've found so far for making a table's body scroll is by splitting the table up into two tables contained in their own <div> tags , using one table for the <thead> section and one for the <tbody> section.

Right now I'm having trouble figuring out the best way to implement the javascript that does this though. I can use document.getElementsByTagName("table") to get a collection of all the tables in the document. Once I have this I can extract the table header and table body for use in modifying the table into the form mentioned earlier. I'd like to be able to make this javascript capable of scanning any html document for tables of a certain class so they can be made into scrolling tables. My question is how do I make an array that contains only the tables that are meant to be transformed? I suppose my actual question is how do I declare an array of the appropriate object type so I can assign table elements to it based on their class?

Another question is once I have the tables and I know what I want to replace them with how would I cut out just the table and paste in the new html? Should I try to find out the parent node of the table and then delete the table node? How would I know which table node to delete if there was more than one in its parent node?

Matthew Leverton

To answer one question:

var tables = []; // create an empty array

var e = document.getElementsByTagName("table"); // find all tables
for (var i = 0; i < e.length; ++i)              // loop through them
  if (e.className.indexOf("splitTable") != -1)  // check its class name
    tables.push(e);                             // add it to the array

// now loop through the array and work on the tables
for (var i = 0; i < tables.length; ++i)
  splitTable(tables<i>);

You don't declare types of arrays or any other variable. An array can hold any mix of values.

Note that calls like getElementsByTagName() may return an active list, which can be confusing. For instance:

var e = document.getElementsByTagName("table"); // find all tables
alert(e.length); 
document.body.appendChild(document.createElement("table")); // add another table
alert(e.length); // should be one more than the previous call

That's why it's best to add them to an array if you plan on doing any modifications (which you are).

Note that if you were using some 3rd party JavaScript library it may be as simple as:

document.getElementsByClassName("splitTable").each(function(t)
{
  splitTable(t);
});

Edgar Reynaldo

Okay , I'm making some sort of progress I think.

I've got an array of just the tables that have the appropriate class attribute and I'm working on preserving the rest of the attributes for the table to be passed on to the transformed tables. However , I can't seem to figure out how to use the javascript string object replace method very well. I'd like to preserve the other classes that the table has if there are any so I've been trying this on the class node :

var classnodevalue = classnode.nodeValue;
if (classnodevalue == "makescroll") {
  table_attributes.removeNamedItem("class");
  alert("Removed class attribute from table");
} else {
  // this doesn't work
  classnodevalue.replace(/makescroll/ , "");
  // this doesn't work either
  classnodevalue.replace("makescroll" , "");

  classnode.nodeValue = classnodevalue;
}

I've been going by what's here : w3schools javascript string replace reference
I've tried their editable examples but I can't get it to actually modify the string. It looks like the replace method returns a string that has had part of it replaced , but it doesn't modify the string itself. Anyone know what I'm doing wrong?

- Update -
I ditched the replace method and I'm using substr() instead now and it works fine to build a new string minus the 'makescroll'. Note that I won't actually be removing the class attribute of the table but replacing the table node entirely.

This is a valid regular expression right?

/makescroll/

I've never used them before and they look pretty bizarre. Anyway , on to building the new tables.

Matthew Leverton

replace() doesn't modify the string.

I wouldn't necessarily remove the class name. It could be useful for styling the table via CSS. But in general, it's handy to create some functions called removeClassName(), hasClassName(), and addClassName().

e.g.,

function removeClassName(e, className)
{
  e.className = e.className
   .replace(new RegExp("(^|\\s+)" + className + "($|\\s+)"), " ")
   .replace(/^\s+|\s+$/g,"");
}

That would remove the class name and trim the white space.

bamccaig
Matthew Leverton said:

replace() doesn't modify the string.

This caught me a few days ago... :)

ImLeftFooted

Matthew's code:

if (e.className.indexOf("splitTable") != -1)  // check its class name

I started out thinking a regex would be simpler, but its actually a bit uglier... Anyway, this is slightly more accurate:

if (/(^|\.| )splitTable($|\.| )/.test(e.className))  // check its class name

Here is a way to do it with less typing:

if(/splitTable/.test(e.className))  // check its class name

Matthew Leverton

I didn't want to confuse him with regular expressions at that point. But yes, your second method is a simpler way to do the same thing.

Your first expression is incorrect though. There's no need to include the dot. And the HTML might have any sort of whitespace separating the class names. Browsers may internally treat them as a single space, but that's not guaranteed.

This is why I wrote:

Quote:

it's handy to create some functions called removeClassName(), hasClassName(), and addClassName().

And the more you start using JS, the more you realize all of these common things have already been packaged nicely into third party libraries. They may add about 35K of overhead, but they remove a lot of headaches and shorten your code up considerably.

ImLeftFooted

I was trying to catch stuff like this:

<style>
.link.awesome {
 ...
}
</style>
<a class="link.awesome">...</a>

But the idea is silly anyway. If you're going to parse CSS stuff you should either 1) keep it simple or 2) do the whole thing. You would have to check tag names and a bunch of other stuff to be CSS-ly accurate.

Matthew Leverton

But it's written as:

<a class="link awesome">...</a>

Nobody is talking about parsing CSS or HTML—just the className property of elements.

Edgar Reynaldo

IE's being a gigantic lamer again.

        if (tableheaders.length > 0) {
          var scrolltableheaderdiv = (tables_to_fix<i>.parentNode).insertBefore(document.createElement("div") , tables_to_fix<i>);
          var scrolltableheaderdivtable = scrolltableheaderdiv.appendChild(document.createElement("table"));
          var scrolltableheaderdivtableheader = scrolltableheaderdivtable.appendChild(document.createElement("thead"));
          var headerattributes = tableheaders[0].attributes;
          for (var j = 0 ; j < headerattributes.length ; j++) {
            newattribute = document.createAttribute(headerattributes.item(j).nodeName);
            newattribute.value = headerattributes.item(j).nodeValue;
            scrolltableheaderdivtableheader.setAttributeNode(newattribute);
          }
          scrolltableheaderdivtableheader.innerHTML = column_specs + tableheaders[0].innerHTML;
        }

IE chokes on this line :

            scrolltableheaderdivtableheader.setAttributeNode(newattribute);

and says :
{"name":"594414","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/4\/0\/40926f010225eb04d6bb686c6df55c0c.jpg","w":453,"h":299,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/4\/0\/40926f010225eb04d6bb686c6df55c0c"}594414
So I guess IE7 doesn't recognize the setAttributeNode method?
Does anyone know a suitable replacement?

Also , I ran my page through the The W3C Markup Validation Service and after fixing an extra slash in my dtd and adding a meta tag for document encoding , it tells me the <nobr> tag is invalid , even though it works on SeaMonkey , FireFox , and IE7. I replaced that with CSS for th and td tags using white-space:pre; and that seems to do nicely and the validator gave it the thumbs up.

So any idea what I can do to find a replacement for the setAttributeNode method that will work cross-browsers?

Matthew Leverton

I see you like extremely long variable names...

In general, you can just do this:

var div = document.createElement("div");
div.attributeName = value;

And on some occasions (due to quirks in browsers), this version is needed:

var div = document.createElement("div");
div.setAttribute("attributeName", value);

Edgar Reynaldo

I changed all the attribute setting to use .setAttribute which gives this :

        if (tableheaders.length > 0) {
          var scrolltableheaderdiv = (tables_to_fix<i>.parentNode).insertBefore(document.createElement("div") , tables_to_fix<i>);
          var scrolltableheaderdivtable = scrolltableheaderdiv.appendChild(document.createElement("table"));
          var scrolltableheaderdivtableheader = scrolltableheaderdivtable.appendChild(document.createElement("thead"));
          var headerattributes = tableheaders[0].attributes;
          for (var j = 0 ; j < headerattributes.length ; j++) {
            scrolltableheaderdivtableheader.setAttribute(headerattributes.item(j).nodeName , headerattributes.item(j).nodeValue);
          }
          scrolltableheaderdivtableheader.innerHTML = column_specs + tableheaders[0].innerHTML;
        }

but then IE gives me this in response :
http://www.allegro.cc/files/attachment/594415

and here's line 118 which IE didn't like :

//
          scrolltableheaderdivtableheader.innerHTML = column_specs + tableheaders[0].innerHTML;
//

If I use this to set an attribute then how do I set the attribute's value? :

element.attributeName = section.item(j).nodeName;

Or did you mean that I should say

element."actualattribute" = section.item(j).nodeValue;

where "actualattribute" is a hard-coded string literal?

I don't think this would work :

element.(section.item(j).nodeName) = section.item(j).nodeValue;

All I want to do is to make sure that I pass on whatever attributes the original table's header , footer , and body had on to the new <div><table><thead>/// , <div><table><tbody>/// , <div><table><tfoot>/// elements.

Edit
Maybe I should just be using .childNodes and loop through them using .appendChild?

Matthew Leverton
MSDN on innerHTML said:

The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR. The property has no default value.

Your code is too verbose for me to read. So that may or may not apply to what you are doing. IE won't let you table.innerHTML = "<tr> ..." although you could do something like div.innerHTML = "<table> ... </table>".

In fifty words or less, what is the purpose of your above code snippet?

Edgar Reynaldo

IE sucks.

My purpose :
Transfer each of the original table's thead , tfoot , and tbody into a new <div><table> for each of them. I want to preserve the attributes of the original table and preserve the attributes of the thead , tfoot , and tbody elements as well.

Matthew Leverton

You could do something like:

var t2 = t1.cloneNode(true);

But I don't know why you would need to clone an entire table. It seems to me that (if we are talking about the original subject) all you would have to do is create a second table, remove the THEAD from the original table, and append it to the second table (which would precede the original table in the DOM).

Then resize the table headers to fit the widths of the columns in the original table.

Edgar Reynaldo

Yes , that would be ideal , I agree.

The problem is that to get proper scrolling in all the browsers , I have to include the table body in a separate <div> with overflow:auto; and a height to get it to scroll properly in all the browsers.

The trouble I run into is that when I have the list of tables to modify , if I use tables_to_fix.getElementsByTagName(thead or tfoot or tbody) then how do I copy that entire element into the new table? Is an element also a node itself? Could I clone it and then use .appendChild(clone) in the new table?

I suppose another option is to get the childNodes of the original table and then filter them into thead , tfoot , and tbody nodes by checking .nodeName so I can use them with .appendChild(). Would I need to clone those then?

Basically , my overall objective is to preserve the original formatting of the entire table through it's transformation into this format :

1<div>
2 <table>
3 <thead>
4 </thead>
5 </table>
6</div>
7<div style="overflow:auto; height:100px;">
8 <table>
9 <tbody>
10 </tbody>
11 </table>
12</div>
13<div>
14 <table>
15 <tfoot>
16 </tfoot>
17 </table>
18</div>

One thing I don't understand though is that a <div> will shrink to fit it's contents vertically , but why not horizontally as well? So I have to set their widths also. Not to mention that SeaMonkey's vertical scroll bars are 15 pixels wide while FireFox and IE's scroll bars are 17 pixels wide.

Edit
Okay , I figured out that getElementsByTagName returns a NodeList of element nodes. Appending a cloned node to the new table is working fine , but there still remains the matter of transferring the attributes of the old table to the new table. The point is that if the original table had CSS , attributes , whatever , I want to preserve that. I realize that I'll have to make some modifications to the table's border frames so that borders don't appear between the table header and body and between the table body and footer but I guess that's the way it goes.

Edit2
Turns out that transferring the attributes of the table wasn't that hard after all. I used

var table_prototype = tables_to_fix<i>.cloneNode(false);
headerdiv.appendChild(table_prototype.cloneNode(true));

and fixed up table_prototype's class attributes to remove the makescroll class.

Now working on setting the column widths among the different div tables using a clone of a new <colgroup> tag that's been set with the different column widths.
Now , how to simply fix up each div table's border frames and margins.

Edit3
From MSDN STYLE reference page

Quote:

Remarks

This attribute is not accessible through scripting. To access styles through scripting, use the style object.

>:( It turns out that IE doesn't support changing an objects inline style attributes through scripting , only through scripting changes in the document's <head> <style> tag's values. Okay , so to jump through the next IE hoop , I have to edit the innerHTML of the <style> tag. :P

Can anyone see what is wrong with these lines? IE says an unknown runtime error happened in the third line.

      var htmlheads = document.getElementsByTagName("head");
      var headstyles = htmlheads[0].getElementsByTagName("style");
      headstyles[0].innerHTML = headstyles[0].innerHTML + ".scrolldiv {\n\r  overflow:auto;\n\r  height:" + tablebodyheight + ";\n\r}";
//

Did I construct the new string incorrectly?

Edit4
MSDN innerHTML reference page
!@#$ .innerHTML is read only for the <style> tag. >:(
So what am I supposed to do to get this to work in IE? Do I have to link in an external style sheet now? W T F ?

What if I copy the innerHTML out of the style tag , alter it , delete the style node and create a new one with the altered innerHTML? Same problem. @#$%.

Okay , the inner HTML is also contained within it's childNode[0].nodeValue of the style node , at least in FireFox it is. So maybe I can clone the node , alter childNode[0].nodeValue of the clone , and then pull a switcheroo. This is really tiresome. It shouldn't take major innovation just to get a table to scroll properly. Maybe I'll email this thread out to W3C and the browsers and see what they think of this crap.

ImLeftFooted
Quote:

I don't think this would work :

element.(section.item(j).nodeName) = section.item(j).nodeValue;

These two lines are equivalent.

element.shoes = 'worn';
element['shoes'] = 'worn';

.. and stop using innerHTML. It's a hack that should be avoided at nearly all costs.

There are very few legitimate uses for it.

Edgar Reynaldo

That doesn't work to set the style attribute of a <div> tag though.

scrolltablebodydiv.style = "overflow:auto; height:" + tablebodyheight + "px;";

In IE7 it tells me 'member not found' for that line.
In SeaMonkey and FireFox it tells me I'm 'setting a property that only has a getter'.

I can set the class attribute of the div but then I have to have the class defined outside of the script and I'd like to have it added to the inline <style> tag of the page , which I have not found a way to do considering the entire <style> tag object is read-only in Internet Explorer. Any suggestions?

Matthew Leverton

You have to set the properties individually:

div.style.overflow = "auto";
div.style.height = tablebodyheight + "px";

Any property that has a dash just uses upper case letters. e.g., max-width becomes maxWidth.

Edgar Reynaldo

Awesome , that did it , even in IE7! Thanks! Now I don't need to mess about with the <style> tag element. Do you know if/how that is possible in IE7?

Matthew Leverton

Google on document.styleSheets. There is the standard W3C way and the IE way. It's not widely used though.

bamccaig
Dustin Dettmer said:

.. and stop using innerHTML. It's a hack that should be avoided at nearly all costs.

I learned this the hard way. :-/

Edgar Reynaldo

I had to know this wouldn't be as simple as adding in a <colgroup> node to each new table. IE7 decided that when there's a <col width="#px"> tag in a <colgroup> of a table that only the inner section of a <th> or <td> tag should be that wide. Firefox decided that the entire column including padding and border should be that wide. Why can't there just be one !@#$ way to do everything in all the browsers?

Should I just manually set the widths of each and every <th> and <td> tag?

Matthew Leverton
Quote:

Should I just manually set the widths of each and every <th> and <td> tag?

Just set the widths on the first row of the tables. (I'm assume there are no colspans.)

Thread #594857. Printed from Allegro.cc