|
Writing HTML | About | FAQ | References | Tags | Lessons | previous | next |27b. JavaScript : Dynamic Content
Let's Increase our Dosage... ObjectivesAfter this lesson you will be able to:
LessonNote: 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.
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:
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: Now we will insert the footer into our Volcano Web HTML documents.
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: 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.
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 ContentNow 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: 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.
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 WorkCompare 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! ReviewReview topics for this lesson:
Independent PracticeCopy 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 |