Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Objects

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Final JavaScript Example

The past few chapters have explored many JavaScript concepts and how they can be applied on the web.

Final JavaScript Example


The past few chapters have explored many JavaScript concepts and how they can be applied on the web. The next JavaScript example combines many of these concepts into a single web page. Figure 11.16 uses functions, cookies, arrays, loops, the Date object, the window object and the document object to create a sample welcome screen containing a personalized greeting, a short quiz, a random image and a random quotation. We have seen all of these concepts before, but this example illustrates how they work together on one web page.


      <?xml version = "1.0" encoding = "utf-8"?>


      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"




      <!-- Fig. 11.16: final.html -->


      <!-- Rich welcome page using several JavaScript concepts. -->


      <html xmlns = "">




      <title>Putting It All Together</title>


        <script type = "text/javascript">



        var now = new Date(); // current date and time


        var hour = now.getHours(); // current hour

        // array with names of the images that will be randomly selected


var pictures = [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ];

        // array with the quotes that will be randomly selected


var quotes = [ "Form ever follows function.<br/>" +

" Louis Henri Sullivan", "E pluribus unum." +

" (One composed    of many.) <br/> Virgil",     "Is it a" +

" world to hide    virtues in?<br/> William     Shakespeare" ];

        // write the current date and time to the web page


        document.write( "<p>" + now.toLocaleString() + "<br/></p>" );


        // determine whether it is morning


if ( hour < 12 )

document.write( "<h2>Good Morning, " );



hour = hour - 12; // convert from 24-hour clock to PM time


// determine whether it is afternoon or evening

if ( hour < 6 )

document.write( "<h2>Good Afternoon, " );


document.write( "<h2>Good Evening, " );

} // end else

        // determine whether there is a cookie


        if ( document.cookie )


// convert escape characters in the cookie string to their

// English notation

var myCookie = unescape( document.cookie );


// split the cookie into tokens using = as delimiter

var cookieTokens = myCookie.split( "=" ); 


// set name to the part of the cookie that follows the = sign

        name = cookieTokens[ 1 ];


        } // end if



// if there was    no cookie, ask the user to input a name

name = window.prompt( "Please enter your name", "Paul" );


//       escape special characters in the name string

//       and add name    to the cookie

         document.cookie = "name =" + escape( name );


         } // end else


         // write the greeting to the page



         name + ", welcome to JavaScript programming!</h2>" );


         // write the link for deleting the cookie to the page


         document.writeln( "<a href = \"javascript:wrongPerson()\" > " +

         "Click here if you are not " + name + "</a><br/>" );


         // write the random image to the page


         document.write ( "<img src = \"" +

         pictures[ Math.floor( Math.random() * 7 ) ] +

         ".gif\" /> <br/>" );

        // write the random quote to the page


        document.write ( quotes[ Math.floor( Math.random() * 3 ) ] );


        // create a window with all the quotes in it


        function allQuotes()


// create the child window for the quotes

var quoteWindow = "", "", "resizable=yes, " +

         "toolbar=no, menubar=no, status=no, location=no," +

         " scrollBars=yes" );

quoteWindow.document.write( "<p>" )


         // loop through all quotes and write them in the new window

         for ( var i = 0; i < quotes.length; i++ )

         quoteWindow.document.write( ( i + 1 ) + ".) " +

         quotes[ i ] + "<br/><br/>");


// write a close link to the new window

quoteWindow.document.write( "</p><br/><a href = " +

         "\"javascript:window.close()\">Close this window</a>" );

} // end function allQuotes

        // reset the document's cookie if wrong person


        function wrongPerson()



        // reset the cookie


document.cookie= "name=null;" +

" expires=Thu, 01-Jan-95 00:00:01 GMT";

        // reload the page to get a new name after removing the cookie




        } // end function wrongPerson

        // open a new window with the quiz2.html file in it


        function openQuiz()


  "quiz2.html", "", "toolbar = no, " + "menubar = no, scrollBars = no" );


        } // end function openQuiz

        // -->







        <p><a href = "javascript:allQuotes()">View all quotes</a></p>


        <p id = "quizSpot">

               <a href = "javascript:openQuiz()">Please take our quiz</a></p>


        <script type = "text/javascript">


        // variable that gets the last modification date and time


        var modDate = new Date( document.lastModified );

        // write the last modified date and time to the page


        document.write ( "This page was last modified " +


        modDate.toLocaleString() );







Fig. 11.16 | Rich welcome page using several JavaScript concepts.

The script that builds most of this page starts in line 10. Lines 12–13 declare variables needed for determining the time of day. Lines 16–23 create two arrays from which content is randomly selected. This web page contains both an image (whose filename is randomly selected from the pictures array) and a quote (whose text is randomly selected from the quotes array). Line 26 writes the user’s local date and time to the web page using the Date object’s toLocaleString method. Lines 29–40 display a time-sensitive greeting using the same code as Fig. 6.17. The script either uses an existing cookie to obtain the user’s name (lines 43–54) or prompts the user for a name, which the script then stores in a new cookie (lines 55–63). Lines 66–67 write the greeting to the web page, and lines 70–71 produce the link for resetting the cookie. This is the same code used in Fig. 11.15 to manipulate cookies. Lines 74–79 write the random image and random quote to the web page. The script chooses each by randomly selecting an index into each array. This code is similar to the code used in Fig. 10.7 to display a random image using an array.


Function allQuotes (lines 82–98) uses the window object and a for loop to open a new window containing all the quotes in the quotes array. Lines 85–87 create a new window called quoteWindow. The script does not assign a URL or a name to this window, but it does specify the window features to display. Line 88 opens a new paragraph in quoteWindow. A for loop (lines 91–93) traverses the quotes array and writes each quote to quoteWindow. Lines 96–97 close the paragraph in quoteWindow, insert a new line and add a link at the bottom of the page that allows the user to close the window. Note that all-Quotes generates a web page and opens it in an entirely new window with JavaScript.


Function wrongPerson (lines 101–109) resets the cookie storing the user’s name. This function is identical to function wrongPerson in Fig. 11.15.


Function openQuiz (lines 112–116) opens a new window to display a sample quiz. Using the method, the script creates a new window containing quiz2.html (lines 114–115). We discuss quiz2.html later in this section.

The primary script ends in line 118, and the body of the XHTML document begins in line 120. Line 121 creates the link that calls function allQuotes when clicked. Lines 123–124 create a paragraph element containing the attribute id = "quizSpot". This para-graph contains a link that calls function openQuiz.


Lines 126–133 contain a second script. This script appears in the XHTML docu-ment’s body because it adds a dynamic footer to the page, which must appear after the static XHTML content contained in the first part of the body. This script creates another instance of the Date object, but the date is set to the last modified date and time of the XHTML document, rather than the current date and time (line 128). The script obtains the last modified date and time using property document.lastModified. Lines 131–132 add this information to the web page. Note that the last modified date and time appear at the bottom of the page, after the rest of the body content. If this script were in the head element, this information would be displayed before the entire body of the XHTML doc-ument. Lines 133–135 close the script, the body and the XHTML document.


The Quiz Page

The quiz used in this example is in a separate XHTML document named quiz2.html (Fig. 11.17). This document is similar to quiz.html in Fig. 10.14. The quiz in this exam-ple differs from the quiz in Fig. 10.14 in that it shows the result in the main window in the example, whereas the earlier quiz example alerts the result. After the Submit button in the quiz window is clicked, the main window changes to reflect that the quiz was taken, and the quiz window closes.


      <?xml version = "1.0" encoding = "utf-8"?>


      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"




      <!-- Fig. 11.17: quiz2.html -->


      <!-- Online quiz in a child window. -->


      <html xmlns = "">




      <title>Online Quiz</title>


        <script type = "text/JavaScript">



        function checkAnswers()


// determine whether the answer is correct

if ( document.getElementById( "myQuiz" ).elements[1].checked )

          window.opener.document.getElementById( "quizSpot" ).

          innerHTML = "Congratulations, your answer is correct";   

else // if the answer is incorrect

          window.opener.document.getElementById( "quizSpot" ).

          innerHTML = "Your answer is incorrect. " +

          "Please try again <br /> <a href = " +

          \"javascript:openQuiz()\">Please take our quiz</a>";





} // end function checkAnswers









        <form id = "myQuiz" action = "javascript:checkAnswers()">


<p>Select the name of the tip that goes with the

image shown:<br />

<img src = "EPT.gif" alt = "mystery tip"/>

<br />


<input type = "radio" name = "radiobutton" value = "CPE" />

<label>Common Programming Error</label>


<input type = "radio" name = "radiobutton" value = "EPT" />

<label>Error-Prevention Tip</label>


<input type = "radio" name = "radiobutton" value = "PERF" />

<label>Performance Tip</label>


<input type = "radio" name = "radiobutton" value = "PORT" />

<label>Portability Tip</label><br />


<input type = "submit" name = "Submit" value = "Submit" />

        <input type = "reset" name = "reset" value = "Reset" />








Lines 15–22 of this script check the user’s answer and output the result to the main window. Lines 16–17 use window.opener to write to the main window. The property window.opener always contains a reference to the window that opened the current window, if such a window exists. Lines 16–17 write to property window.opener.document.getElementById("quizSpot").innerHTML. Recall that quizSpot is the id of the paragraph in the main window that contains the link to open the quiz. Property innerHTML refers to the HTML code inside the quizSpot paragraph (i.e., the code between <p> and </p>). Modifying the innerHTML property dynamically changes the XHTML code in the paragraph. Thus, when lines 16–17 execute, the link in the main window disappears, and the string "Congratulations, your answer is correct." appears. Lines 19– 22 modify window.opener.document.getElementById("quizSpot").innerHTML. Lines 19–22 use the same technique to display "Your answer is incorrect. Please try again", followed by a link to try the quiz again.


After checking the quiz answer, the script gives focus to the main window (i.e., puts the main window in the foreground, on top of any other open browser windows), using the method focus of the main window’s window object. The property window.opener ref-erences the main window, so window.opener.focus() (line 24) gives the main window focus, allowing the user to see the changes made to the text of the main window’s quizSpot paragraph. Finally, the script closes the quiz window, using method window.close (line 25).


Lines 28–29 close the script and head elements of the XHTML document. Line 30 opens the body of the XHTML document. The body contains the form, image, text labels and radio buttons that comprise the quiz. Lines 52–54 close the form, the body and the XHTML document.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020; All Rights Reserved. Developed by Therithal info, Chennai.