views:

263

answers:

3

I'm trying to build a grid the size of the browser window that has 20x20px squares. My first idea was to just construct a table with the following code, but IE8 (in any mode) will not render the cells unless they have non-white space content. According to this, it will if it has a  , but from my testing, it only works if the table is in the original DOM - not from javascript.


dojo.ready(function(){
    var grid = dojo.byId("grid");
    var tr;
    for(var i=0; i<20; i++) {
        tr = dojo.create("tr", null, grid);
        for(var j=0; j<20; j++) {
            var td =dojo.create("td", {innerHTML: "&nbsp;"}, tr);
            dojo.style(td, {border: "solid", height: "20px", width: "20px"});
        }
    }
});
...
<table id="grid" style="border-collapse: collapse;"></table>

After giving up on that approach, I decided to try google-closure's vector graphics library - thinking vector drawing would be the more appropriate solution in principle since tables are not intended for this.. I got it working cross browser, but for a decent sized grid (say 1000x1000) the load times and memory utilization are outrageous. I suppose it was not designed to be used for this either:


var graphics = goog.graphics.createGraphics(800, 800);
var path, stroke = new goog.graphics.Stroke(1, "gray");

for(var x=0; x<65; x++) {
 for(var y=0; y<65; y++) {
     path = new goog.graphics.Path();
     path.moveTo(0, y*20);
     path.lineTo(800, y*20);
     graphics.drawPath(path, stroke);

     path = new goog.graphics.Path();
     path.moveTo(x*20, 0);
     path.lineTo(x*20, 800);
     graphics.drawPath(path, stroke);
 }
}

graphics.render(document.byId("grid"));
...

Maybe the pragmatic solution would be to create a 20x20px image and repeatedly insert that?

+1  A: 

Does it have to be programmatically? Because with a 20x20 Pixel GIF as a background image, with a line to the right and bottom, you'd be done in five minutes. It's cross browser, and works on huge areas as well.

Edit: You had that idea already at the end of your question. Yes, I think that's the easiest way.

Pekka
+1  A: 

Sometimes I do things the hard way...

body {background-image: url(grid-cell.png); background-repeat: repeat;}

^^

Robert
A: 

I'm not sure if the dojo library fixes IE's particular issues with tables when you create them dynamically but if not, you'll need to add a TBODY tag before adding the rows or IE will fail to render the table properly.

scunliffe