View Full Version : Dynamic Image Table Loop Advice Needed

05-29-2006, 10:39 PM
I am trying to create a table of images dynamically from a DOM which sources an XML file.

Currently, all of the filenames I am extracting from the DOM are successfully being created as <img src attributes, but all of the images are in one table row. What I would like is to have 5 images per row, and the next row continue with the list from the DOM. Hence the result would be 1 image per table cell; five table cells per table row; no repeating images.

What is happening now, however, is that I'm getting the same 5 images in each row. I'm new to javascript, and the loops are boggling me.

--I think I need stop the variable allImgFilenames[i] from resetting each time a new table row is created. But how?

Any help would be greatly appreciated!

<title>Sample Product Gallery</title>
<script language="JavaScript" type="text/JavaScript">
//Load the XML to buffer
var xmldoc=new ActiveXObject("MSXML2.DOMDocument.3.0");
xmldoc.setProperty("SelectionLanguage", "XPath");

var PrintNode = xmldoc.documentElement.selectNodes("./Print");
var allImgFilenames=new Array();
for (var i=0;i<PrintNode.length;i++) {
allImgFilenames.push (PrintNode[i].getElementsByTagName("file")[0].getAttribute("href"));

function start() {
var mybody = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var mytable = document.createElement("table");
var mytablebody = document.createElement("tbody");

// creating all cells
for(var j = 0; j < 1; j++) {
// creates a <tr> element
var mycurrent_row = document.createElement("tr");
for(var i = 0; i < allImgFilenames.length; i++) {
// creates a <td> element
var mycurrent_cell = document.createElement("td");
//creates img tag
var imgTag = document.createElement("img");
//appends img tag to table data node
//Sets src attribute to filename variable
imgTag.src = ("images/" + allImgFilenames[i]);
// appends the cell <td> into the row <tr>
// appends the row <tr> into <tbody>
// appends <tbody> into <table>
// appends <table> into <body>
// sets the border attribute of mytable to 2;
mytable.setAttribute("border", "0");
<body onload="start()">


Sample XML:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="Printlist.xsl"?>

<PrintName>Farmhouse in Spring</PrintName>
<file href="spring_234farm.jpg"></file>

<PrintName>Mr. Bunny</PrintName>
<file href="spring_easter_bunny_small.jpg"></file>

<PrintName>Easter Bunny Basket</PrintName>
<file href="spring_bunny_basket.jpg"></file>