Traversing Tables with DOM Table Methods


/ Published in: CSS
Save to your folder(s)

A table is nothing but a set of blocks. A simple grid. There are a lot of web apps where the storage of data in a grid would make functions much easier to deal with using simple scripting. If only it was easy to target cells and traverse between them like a spreadsheet.


Copy this code and paste it in your HTML
  1. // these globals make the whole thing more flexible
  2. lastRow=-1;
  3. lastCol=-1;
  4. destRow=-1;
  5. destCol=-1;
  6. // first we set up the loop
  7. function traverse(x,y,xx,yy)
  8. {
  9. lastRow=x;
  10. lastCol=y;
  11. destRow=xx;
  12. destCol=yy;
  13. Tcells[lastRow][lastCol].style.backgroundColor='red';
  14. Tcells[lastRow][lastCol].style.color='white';
  15. Tcells[destRow][destCol].style.backgroundColor='yellow';
  16. Tcells[destRow][destCol].style.color='blue';
  17. CTL=setTimeout('traverseLoop()',500);
  18. }
  19. // now the loop executes until the traverse is completed
  20. function traverseLoop()
  21. {
  22. if (lastRow==destRow && lastCol==destCol) // we are at the end of the traverse
  23. {
  24. Tcells[destRow][destCol].style.backgroundColor='red';
  25. Tcells[destRow][destCol].style.color='white';
  26. return;
  27. }
  28. if (lastRow!=destRow) // set the row for the new location
  29. {
  30. lastRow=(lastRow<destRow) ? lastRow+1 : lastRow-1;
  31. }
  32. if (lastCol!=destCol) // set the column for the new location
  33. {
  34. lastCol=(lastCol<destCol) ? lastCol+1 : lastCol-1;
  35. }
  36. Tcells[lastRow][lastCol].style.backgroundColor='green';
  37. Tcells[lastRow][lastCol].style.color='orange';
  38. CTL=setTimeout('traverseLoop()',500); // loop timing is .5 seconds
  39. }

URL: http://coboldinosaur.com/pages/Table_Traverse.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.