您的位置:寻梦网首页编程乐园HTML园地HOME page制作初步
Writing HTML | About | FAQ | References | Tags | Lessons | previous | next |

27b. JavaScript : Dynamic Content

Let's Increase our Dosage...

write dynamic content to a page...

different messages for different conditions...


Objectives

After this lesson you will be able to:

  • Write the JavaScript code to dynamically write any HTML code
  • Write the JavaScript code to display automatically the web page title, the URL and file modification dates
  • Write the JavaScript code to print a formatted date
  • Write the JavaScript code to determine the current web browser brand and version

Lesson

Note: If you do not have the working documents from the previous lessons, download a copy now.

We have reminded you before that as an HTML document loads into a web browser, it is interpreted as the browser reads in more data. For HTMl, this means that as soon as the browser gets enough information to display something, it tries to do that, even as it reads in the remainder of the document.

When we refer to dynamic content that you can write in JavaScript, that means that the web browser can do more than just "read and display", "read and display"... as it reads in JavaScript code among your HTML, it can make decisions based upon the way the code is set up, test against some built in functions, and then write different HTML code according to its programmed instructions. It may even be programmed to do something randomly different every time the page loads.

It makes your web pages a bit more "intelligent" than just sitting there looking pretty!

We can use JavaScript to write any other kind of HTML content using the format:

  document.write('xxxxxxxx xxxxxxxxxx');
  document.write('xxxx xxxxxxx xxxxxxx xxxxx');
  document.write('xx xx xxxxxxxxxxxx xx');

Each line of this code writes a chunk of HTML, that is everything inside of the single quote characters. This series of JavaScript statements:

  document.write('<h1>Wide World of Cheese</h1>')
  document.write('<b><i>Not everyone in this world likes cheese');
  document.write('as much as I!<i></b><br> -- Colby Jack (1903)');

will produce the exact same display as this chunk of HTML:

  <h1>Wide World of Cheese</h1>
  <b><i>Not everyone in this world likes cheese 
  as much as I!<i></b><br> -- Colby Jack (1903)

Now if this was all there was to JavaScript, we would not even be trying to teach it to you! JavaScript provides other types of information that you can display that is not available via HTML. There are built in functions that can provide the current date and time, information about the user's web browser, and more as we will soon see. But even more than this, we can set up logical statements to test, so that we can do things like:

If today is Tuesday or Wednesday and the time is after 12:00 PM then display this custom message morning greeting; but if it is before 12:00 PM, then display this different message for the afternoon. But if it is Friday, at any time, let's display a different type of message no matter what time of day it is. Any other day or time, just display a standard "Have a nice day" message.

JavaScript code gives us some flexibility to create dynamic content that can behave and display differently to the viewer.

The first thing we will do is to write a series of JavaScript statements that will create the footers of all of our documents-- but unlike the ones to date that we have written by hand, this same block of HTML/JavaScript can be cut and pasted into every document but will also dynamically print (with examples for this page shown in parentheses):

Not all web servers provide accurate document modification dates, item (c), and typically when you are testing documents on your desktop computer, you will not be able to get this information and it would print some erroneous date like January 1900. We will show you how to test for these conditions. Item (d) is extremely useful because if we were to move our web pages to different web servers or re-arrange our site, the URL would be updated automatically.

The template for our "standard" web page footer for the Volcano Web project looks like the code below. We'll present it first section by section with some explanations. It's not critical that you understand exactly how it works, since when you incorporate it into your working pages, it will be simply a cut and paste operation.

JavaScript Footers
HTML code explanation
<!-- start of Volcano Web standard footers -->
<SCRIPT LANGUAGE="JavaScript">
<!-- hide scripts from old browsers
Marks the beginning of the footer area, with proper JavaScript tags
document.write('<p><hr>
<FONT FACE="helvetica,arial" size=-1>
<i>Volcano Web:</i> <B>');
Horizontal rule, begin text font size and main web site title
document.write(document.title + '</B><BR>');
Write the current document title
document.write('created by Lorrie Lava, ');
document.write('<A HREF="mailto:lava@pele.bigu.edu?subject=' 
+ document.title + '">');
document.write('lava@pele.bigu.edu</A><br>');
Credits for page with an e-mail link that automatically inserts the page title into the subject line.
document.write('Volcanic Studies, 
<A HREF="http://www.bigu.edu/">');
document.write('Big University</A><p>');</tt></font>
More static content.
// append a modification date only if
// server provides a valid date
if (Date.parse(document.lastModified) > 0) {
  document.write('<B>last modified: </B>' 
  + document.lastModified + '<BR>');
}
This looks tricky. We have set up a conditional test on the value that is returned by document.lastModified, and if it is valid (a non zero return from a function we use called Date.parse, we write the modification date. If we do not get a valid date, this whole block is ignored.
document.write('<B>URL: </B>' 
  + document.location.href + '</FONT><P>');
Write the URL of the current document given by the value returned by the JavaScript variable document.location.href
// done hiding from old browsers -->
</SCRIPT>
<!-- end of Volcano Web standard footers -->
End of the footer code block.

Most of the dynamic content in this examples comes from "properties" of different JavaScript "objects", namely in this case the document object. Each HTML document has built-in identifying pieces of information-- namely it's title, date of last modification, URL, etc. We can query the document object to get and then use this information.

Information we are writing to the page using document.write that is fixed content (strings of text in quotes) and information that is stored in JavaScript variables, like document.title, we join with the "+" sign:

 'Here is some fixed <b>HTML</b> text for the page:' + document.title + '! Nice, eh?'

The "+" sign joins the text together into one longer string, so if we were using it in this lesson page, we would see:

sample web page
Here is some fixed HTML text for the page: 27b. JavaScript- Dynamic Content! Nice, eh?

Our JavaScript footer also uses a "conditional" test ("if this then do that") for the modification date, that looks like:

  if ( some condition to test ) {
    JavaScript statement1;
    JavaScript statement2;
          :
          :
    JavaScript statementN;
  }

which means that if the condition test in the first line's parenthesis results in a TRUE value, we would follow the steps inside the "{" and "}" brackets; if the test is FALSE, we skip these statements. With the power of JavaScript, we can construct very complex conditional tests, but for now we will keep it simple.

This is how our JavaScript footer would look if it were used in this lesson page:

sample web page

Now we will insert the footer into our Volcano Web HTML documents.

  1. First, open your main entry page, index1.html in your HTML editor. (we will not put the footer on our opening "splash" page, index.html).
  2. Delete our old footer HTML content:
    
    <HR>
    <ADDRESS><B>Volcano Web</B><br>
    created by Lorrie Lava, <A HREF="mailto:lava@pele.bigu.edu">lava@pele.bigu.edu</A><p>
    Volcanic Studies, <A HREF="http://www.bigu.edu/">Big University</A><p>
    <TT>last modified: April 1, 1995</TT>
    </ADDRESS>
    <p>
    <tt>URL: http://www.bigu.edu/web/index.html</tt>
    <p>
  3. Replace it with our new JavaScript footer content:
    <!-- start of Volcano Web standard footers -->
    <SCRIPT LANGUAGE="JavaScript">
    <!-- hide  scripts from old browsers
    
    document.write('<p><hr><FONT FACE="helvetica,arial" size=-1><i>Volcano Web:</i> <B>');
    document.write(document.title + '</B><BR>');
    document.write('created by Lorrie Lava, ');
    document.write('<A HREF="mailto:lava@pele.bigu.edu?subject=' 
      + document.title + '">');
    document.write('lava@pele.bigu.edu</A><br>');
    document.write('Volcanic Studies, <A HREF="http://www.bigu.edu/">');
    document.write('Big University</A><p>');
    
    // append a modification date only if server provides a valid date
    if (Date.parse(document.lastModified) > 0) {
        document.write('<B>last modified: </B>' + 
               document.lastModified + '<BR>');
    }
    document.write('<B>URL: </B>' + document.location.href + 
               '</FONT><P>');    
    
    // done hiding from old browsers -->
    </SCRIPT>
    <!-- end of Volcano Web standard footers -->
    NOTE: It is critical that all of your JavaScript statements are on a single line, starting from document.write('... and ending with ');, If you have extra RETURN characters in the code, it will not work. Also, be sure the structure of the if (...) { block of statements is exactly as shown above.

    JavaScript is even more picky than HTML about typos! And there is more room for mistakes with the ways quote characters are used.
  4. Save and Reload in your web browser. If there are no JavaScript errors, then see if the content in the footer appears similar to the example shown above (the URL should be different, of course, it will generate a URL that may include your local hard drive). If you do get JavaScript errors, compare your code in detail with the example. Finally, if nothing appears, try reload again. If this does not work, most likely your JavaScript code is missing a quote or a ">".
  5. Now you are ready to cut and paste the new JavaScript footer into the same areas of these other files that are part of your Volcano Web:
    1. explode.html
    2. height.html
    3. intro.html
    4. mars.html
    5. msh.html
    6. term.html
    7. usa.html

We have not yet updated the footer that is part of our project page, which we broke into a framed set up in lesson 26. You may think that all we have to do is to paste it into the frame on that page for the footer document, proj_footer.html. But the problem here is that the JavaScript function document.location.href will not display the URL for the framed web page, "...project.html" but for the footer document. Also, many browsers return the file name rather than the page title for document.title of a framed web page. We would end up with something that looked like:

sample web page

To get around this problem we could go back to a regular HTML footer... or use some more creative (and complex) JavaScript. We will take the second option, using JavaScript to "extract" the information we wish to display from the document object.

  1. Open your proj_footer.html in your text editor
  2. Delete the old footer content as we did in the above sections.
  3. Replace it with this JavaScript code:
    
    <!-- start of Volcano Web standard footers -->
    <SCRIPT LANGUAGE="JavaScript">
    <!-- hide  scripts from old browsers
    
    document.write('<p><hr><FONT FACE="helvetica,arial" size=-1><i>Volcano Web:</i> <B>');
    document.write('Project</B><BR>');
    document.write('created by Lorrie Lava, ');
    document.write('<A HREF="mailto:lava@pele.bigu.edu?subject=Project">');
    document.write('lava@pele.bigu.edu</A><br>');
    document.write('Volcanic Studies, <A HREF="http://www.bigu.edu/">');
    document.write('Big University</A><p>');
    
    // append a modification date only if server provides a valid date
    if (Date.parse(document.lastModified) > 0) {
        document.write('<B>last modified: </B>' 
          + document.lastModified + '<BR>');
    }
    
    // extract proper URL from this file name, assuming this file
    // is "proj_footer.html" or "proj_footer.htm"
    // and the proper URL for the frameset is "proj.html" or "proj.htm"
    myURL = document.location.href;
    
    // Get the suffix on the file name (everything after "_footer")
    myExt = myURL.substring(myURL.indexOf("_footer") + 7, myURL.length) 
    
    // Get the part of the URL that goes up to "proj"
    myUrl = myURL.substring(0,myURL.indexOf("_footer"))
    
    // Assemble the appropriate string
    document.write('<B>URL: </B>' + myUrl + myExt + '</FONT><P>');    
    
    // done hiding from old browsers -->
    </SCRIPT>
    <!-- end of Volcano Web standard footers -->
    
  4. Save this document and Reload the main frame web page, project.html in your web browser.

In this example, we have used some more advanced JavaScript functions to do things like extract portions of one string from another, and finding the location of a particular character in a string. Unfortunately, explainign it all is beyond what we can cover here; please see our references for recommended tutorials and resources.

More Dynamic Content

Now we will show you even more things to do with JavaScript. Another built-in functionality is the ability to use the viewer's computer to get the date and time (assuming they have it set correctly!). We can use this to "stamp" a greeting on the front page. We could write "Good Morning!", "Good Afternoon!", "Good Evening!", or "Isn't it Late to be At the Computer?" depending on what time of day the function returns to us through JavaScript.

The first thing you have to do is to create a Date object in JavaScript:

  var today = new Date(); 

Now we have something called today that we can reference to get information about the date and time. JavaScript stores this information internally as something like the number of seconds since a reference date such as January 1, 1900. But the JavaScript Date object has properties that allow us to get the month, day, year, hour, minute, second, etc.

One of the easier object properties to use is Date.toLocaleString() which will display the date in accordance to the settings of the user's computer (since there are different conventions for displaying dates in other countries). So we could write code like:

  var today = new Date(); 

  document.write('According to my JavaScript watch, it is ' + today.toLocaleString() )'

which would display like:

sample web page

If you reload this lesson page, the time on the display will change. Note that the date format returned is dependent on the type of computer.

JavaScript offers other information about the web browser that the viewer is using, via the navigator object, so we can test which web browser it is (NetScape, Internet Explorer, etc) as well as which version. This is useful if you are using features in a web page that require certain web browsers-- you can use JavaScript to "test" the set up and display information specific for different browsers or versions.

We will now use JavaScript Date objects and navigator objects to display a customized greeting in our main page. we will do some extra work so that JavaScript displays the day of the week ("Monday, Tuesday", etc) and then write some message if the viewer has an older browser version. We briefly explain below what the code is doing, but if you just want to try it out, you may copy, paste, and test in your browser.

  1. Open the index1.html document in your text editor.
  2. Between the part that reads:
    In this lesson you will use the Internet
    to research information on volcanoes and then write a report on your
    results.
    and
    <br clear=left>
    <hr>
    <p align=center>
    insert this JavaScript code:
    <p>
    <SCRIPT LANGUAGE="JavaScript">
    <!-- hide from old browsers
    
    // get date object
    var today = new Date(); 
    var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    
    // write the date 
    document.write('Welcome on this fine <b>' + days[today.getDay()]);
    document.write('</b>, or more precisely,<br>');
    document.write('<font color="#FFFF33" size=+2><tt>'); 
    document.write(today.toLocaleString() + '</tt></font>');
    
    // write a welcome string acknowledging the browser version
    document.write('<p>We hope you enjoy your web experience with your version of '); 
    document.write(navigator.appName + ' ' + parseFloat(navigator.appVersion));
    
    // write a warning for old web browsers
    if ( parseInt( navigator.appVersion) < 3 ) {
        document.write('<font color=#FFFF33> Hmmm.. that\'s a pretty old version of ');
        document.write(navigator.appName + '! Perhaps it is time to consider an upgrade?</font>');
    }
    
    // done hiding -->
    </SCRIPT>
    NOTE: On the last section of this code, you may see something that looks out of place, a forward slash \ in the word that's. Ths is not a typo! You need this special marker so that JavaScript interprets the single quote as an apostrophe character and not the single quote that marks the end of the JavaScript text string. If you remove this forward slash, the code will generate an error.
  3. Save and Reload.

In this script we first create the Date object and put it in a variable we call today. We then create an "array", or a list of things, called days that contains names of the days of the week.

Arrays are very handy containers because we can refer to items in them like:

    days[2]

where the number in the square brackets indicates the location in the array for the item we are looking for. But watch out! JavaScript starts counting arrays at 0, so days[2] actually returns the third item, or "Tuesday".

Our code writes a welcome text string and then uses the array to extract the correct name of the day. The Date object function today.getDay() returns a number from 0 to 6 that corresponds to which day of the week it is. So we can combine the Date object function and our array of names to print the correct day of the week.

Following this, we use the format provided from today.toLocaleString() to write the full date information.

The next piece prints the browser name ("NetScape", "Internet Explorer") followed by the version returned to us by the function navigator.appVersion, which actually returns a longer descriptive name. By putting that inside a function called parseFloat, it pulls out or "parses" the part of that string that corresponds to a whole number. As a comparison, see:

This last item provides a nicely formatted string to display the browser and version number. The code parseInt(navigator.appVersion) parses out the whole number part of this information. if you look at the last portion of our code above, we test the parseInt value and write an extra warning if it is less than our test value of 3. To see the difference, you should change the 3 to a number higher than your present browser version.

Check Your Work

Compare your web pages with this sample of how it should appear. If your pages are different from the sample or the hypertext links do not work correctly, review the text you entered in the text editor. Note that JavaScript is very sensitive to typographical mistakes -- one missing quote or semi-colon can ruin the page!

Review

Review topics for this lesson:

  1. Why does it matter where in your HTML document you insert JavaScript code for writing dynamic content?
  2. What information can you get from the JavaScript document object? What is the format for printing that information to the web page?
  3. How do you get the current date and time from JavaScript? the day of the week?
  4. Using JavaScript, what information can you get about the web browser?

Independent Practice

Copy the format for the JavaScript footer used here to your own documents and see if you can change the HTML format to match your design.

Can you think of a way to write JavaScript code that would display a different welcome message for every hour of the day? Hint: Use an array to create the text of all your messages, an use the Date.getHours() function to determine the current hour.


Coming Next....

Your JavaScript Doctor gives you the next dose of code... functions and code for opening browser windows of any size and configuration. Where you want them and with as many or as few browser buttons as you like.

GO TO.... | Lesson Index | previous: "JavaScript: Alerts and MouseOvers" | next: "JavaScript: Custom Window Openers" |

Writing HTML: Lesson 27b: A Wee Dose of JavaScript : Dynamic Content
©1994-1999 Maricopa Center for Learning and Instruction (MCLI)
Maricopa Community Colleges



URL: http://www.mcli.dist.maricopa.edu/tut/tut27b.html