Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Writing with Loops

(Netscape and Internet Explorer/Mac)

Sometimes you'll want to get information out of JavaScript objects and display them to the user. Using JavaScript to write the user's Web page on the fly is a useful technique, one you'll find yourself using often. In this example ( Script 3.3 ), you'll use a loop to display all of the plug-ins installed in your browser, and write a list of them out to the browser window.


Script 3.3 You can use loops to step through JavaScript objects and write to the browser window.

To write a Web page using a loop

  1. if (navigator.plugins && navigator.
    U2192.GIF plugins.length > 0) {
    If both of these values are true, continue on with the following code.
  2. document.write("You have the
    U2192.GIF following plugins: <table
    U2192.GIF cellspacing='4' cellpadding='4'>")
    The information on the page will be displayed inside a table, so we'll start it off by writing out the <table> tag here.
  3. document.write("<tr><th bgcolor=
    U2192.GIF '#CCCCCC'>Name<\/th><th bgcolor=
    U2192.GIF '#CCCCCC'>Filename<\/th><th bgcolor=
    U2192.GIF '#CCCCCC'>Description<\/th><\/tr>")
    This line of code writes out the headers for the first row of the table.
  4. for (i=0; i<navigator.plugins.length;
    U2192.GIF i++) {
    This line, as in the previous example, loops through each installed plug-in.
  5. thisPlugin = navigator.plugins[i] Rather than refer to each plug-in by its full name, we set up a temporary variable that saves the value of the plug-in that we're currently interested in.
  6. document.write("<tr valign='top'>
    U2192.GIF <td bgcolor='#CCCCCC'>" +
    This line starts a new row and cell, and writes out the name of the current plug-in.
  7. document.write("<\/td><td bgcolor=
    U2192.GIF '#CCCCCC'>" + thisPlugin.filename)
    The old table cell is ended, a new one begins, and the filename of the plug-in is written to the page.
  8. document.write("<\/td><td bgcolor=
    U2192.GIF '#CCCCCC'>" + thisPlugin.
    U2192.GIF description + "<\/td><\/tr>")
    Another cell ends, a new one begins, and the description of the plug-in finishes off the cell and row.
  9. } This brace ends the loop, and the lines inside are repeated for each plug-in installed in the user's browser.
  10. document.write("<\/table>") When the loop has finished, we write out the ending <table> tag to finish off the code, as shown in Figure 3.5 .

    Figure 3.5 This table of plug-ins was written to the browser window using a loop.

  11. document.write("JavaScript couldn't
    U2192.GIF find any plugins")
    If the user has a browser that doesn't support viewing the plug-ins through JavaScript, this is the message they'll see.
  • + Share This
  • 🔖 Save To Your Account