Sunday 7 August 2011

Viewing JavaScript Output.

A problem I encountered recently was how to actually see the HTML output by JavaScript.  The trouble with producing HTML code from JavaScript is that when you view the source of the rendered page you only get to see the original JavaScript.

For example:  Can you see what is wrong with this JavaScript?
<script type="text/javascript">
  //<!--
  var SquaresAcross=16;
  var SquaresDown=16;
  document.writeln("<table width=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\">");
  for (i=0; i<(SquaresAcross*SquaresDown); i++)
    {
    if ((i%SquaresDown)==0) {document.writeln(" <tr>")};
    document.writeln("   <td width=\"34\" height=\"34\"> <img src=\"pics/maze/maze-11.gif\" alt=\"s"+i+"\" name=\"s"+i+"\" width=\"34\" height=\"34\" id=\"s"+i+"\" /> </td>");
    if ((i%SquaresDown)==(SquaresDown-1)) {document.writeln("  </tr>")};
    }
  document.writeln("</table>");
  //-->
</script>

Is it going to produce the right HTML code?  And if it doesn't but still runs can you see, from the output, what the problem might be?  It would be so convenient to see the HTML it produces but if you load the page into a browser and view the source all you get is the original JavaScript.

There is a solution!

Load the page into a browser and save it to your hard disk.  Then load the saved version into a browser and 'View Source'.  Hey presto! (Or even Ali Bongo if you like.) The HTML output is in the source for the page.

A useful little tip and more is explained at Toxic Drums: View JavaScript Output

Also... If you want to know how to get HTML code in your Blogger post (like the above example) the simple solution is to go to Simple Bits where you can simply put your code into the processor and it spews out the code required for Blogger.  You can work out how to do it after that.

1 comment: