LESSON TWENTY-THREE
FUN WITH JAVASCRIPT

You may read the following sections in their entirety
or use these choices to go directly to a section.

Java versus JavaScript | | Our first interactive JavaScript - The JavaScript Alert pop-up window | | The Confirm and Prompt JavaScript windows | | Personalizing your visitor's name | | Interacting with your visitor's computer clock | | Conclusion -  Want more JavaScript? |


JAVA VERSUS JAVASCRIPT

Both Java and JavaScript are programming languages that resemble a programming language called C. They are both examples of modern Object Oriented Programming (OOP) Languages. They both share a similar syntax and at first glance both appear to be the same. However, there are some very important differences and it is because of these differences that we have in fact two languages - Java and JavaScript. Each of these languages is suited to different applications and environments.

Object Oriented Programming means that the final program is made up of many parts or many objects. For example, a lot of parts (objects) go into making a car and each object is important. However, it's when they are all put together into that final product that counts. Just as many objects make up the whole car, similarly, many objects in an OOP language make up the whole program.

JavaScript is the language of choice for creating interactive web pages. This is because JavaScript is designed as an extension to HTML and is included within HTML codes. Java, on the other hand, is a more general purpose language. While Java can also be used in web page development, it has very little capability to interact with a browser. Yet Java is very capable of creating stand alone applications such as a data base manager that can be run without being part of any web page.

Java was developed by Sun Microsystems. It is closely related to C and C++. To program in Java or to see or include a Java Applet in your browser, you need to have at least Windows 95 or higher and your browser must be at least a 32-bit version of Netscape Navigator 3.0, or at least a 32-bit version of Internet Explorer 3.0. Finally, to do any programming in Java or to test applets, you will need a Java Developers Kit (which you can get from the above Sun Microsystems website).

It is possible to incorporate existing pieces of complied Java code called Applets into a web page by using the APPLET element (discussed in Lesson 19). A Java Applet is a small Java program (hence the term Applet) used mostly to create special effects and interactive events on your web pages such as led signs, clocks, calculators, conversion tables and a host of other interactive events. The <APPLET> element is used to set up a Java applet and only browsers that are Java enabled (that can recognize the APPLET tag) can display the applet. When you use a Java compatible browser to view a web page that contains a Java applet, the applet's code is loaded into the browser and then executed.

One of the basic differences between Java and JavaScript is that JavaScript is highly event driven. It is great at detecting mouse clicks, pointer movements and visitor input. Java on the other hand is not so tightly focused and an Applet may not accept any input at all. And if the Applet does respond to user input, it does not react to other events that might occur outside its "window" or outside its realm. So an Applet is basically a small Java program running in its own window.

Java is a very strict language. All variables must belong to a Java "class" (called an "object") and all functions must be "methods" of a particular object" (recall that we are dealing with an "Object" Oriented Programming language). That is, everything must be part of a class and all Java variables must be declared and typed and this typing is quite strict.

JavaScript, on the other hand, is a less strict language than Java. Because it is a less strict language, it is easier to write and easier to learn. For example, in JavaScript, you can create your own functions and use any variable that is not reserved for another purpose. You can also mix variables due to the fact that these JavaScript variables do not belong to any "type" or class (that is, JavaScript is loosely typed). With JavaScript you do not need to declare variables until you use them. The downside to all this is that it is harder to check for errors in JavaScript. That is, you have more freedom with JavaScript with the result that the program does less error checking for you.

So you can see that in many ways JavaScript and Java are two different languages. There are still many browsers in use today that do not support Java but it is now getting to the point that most browsers do support JavaScript. So if you want to create dynamically interactive web pages, JavaScript is the language to use. If you want to create independent applications that may or may not be delivered through the web, then Java is the way to go.

This lesson will concentrate on a few interactive applications using JavaScript. Although it is quite possible to write JavaScript that will run programs or cause things to happen at a remote server, this lesson concentrates all interactive applications at the client (or visitor) computer - that is, in your visitor's browser with no dependency on a remote server.

WHY LEARN JAVASCRIPT?
When you finish this lesson, you will know whether or not JavaScript is an area you want to pursue further. With most people, when they see an interactive event they like, they will simply copy the code (which is often written in JavaScript) and use it as is. They have no understanding what the code means or why it works - but it works. So they just copy it and use it hoping no one will find out. Copying and using other people's work without permission is really a violation of international copyright laws and has been known to generate lawsuits.

If you have an understanding of JavaScript, you can make up your own interactive events. And if you see something on another website you really like, then you will be able to adapt it to your own situation. Learn JavaScript and you will know what you can change and what you can't change. JavaScript is not difficult to learn if you take a step by step approach. This lesson will only give you a taste of the fun you can have with JavaScript on your web pages - so let's get started with our first example.


top | | bottom |

OUR FIRST INTERACTIVE JAVASCRIPT - THE JAVASCRIPT ALERT POP-UP WINDOW

Did you like the JavaScript Alert window that suddenly popped up when this web page was loaded? If you did not see any box, then one of two things is possible:
  1. You are using a browser older than Netscape Navigator 2.0 or Internet Explorer 3.0. These older browsers do not support JavaScript and so unfortunately the events that occur in this lesson cannot be seen in your browser.
  2. You are using a browser that has had the JavaScript turned off. This will be the case if you are using at least Netscape 2.0 or at least Internet Explorer 3.0. Each browser version has its own way of turning on (also called "enabling") JavaScript. Here are the instructions to turn on JavaScript. If they don't work for your browser and you can't figure out how to do it, please ask someone you know who can help you.
JavaScript, like any computer language, has a number of built-in functions which make programming a little simpler. I used one such function for our JavaScript Alert window. Here is the line that makes up this little interactive window:

<BODY onLoad="window.alert('I sure hope you bookmarked this website!')" BGCOLOR="#FFFFFF" TEXT="#000000">

Note the following points:

  1. This simple statement that makes the JavaScript Alert window is part of the BODY tag. I also like to specify a white background (BGCOLOR="#FFFFFF") with black text (TEXT="#000000") and so I included these specifications with the BODY tag. Remember that the BODY tag indicates the beginning of the BODY of the web page. Remember also that you can only have one BODY tag on a web page.
  2. OnLoad is a called an event handler. OnLoad tells the browser that the event must happen when the web page is first or initially loaded (that is, produce this Alert window onLoading the web page).
  3. When the browser sees window.alert(), it knows what to do. Window is called an object and alert() is called a method of the window object. An object can have many methods and for the window object, alert() is one them. Note that () is simply and opening and closing bracket (in case it is hard to read).
  4. The message is called a parameter and parameters must always be enclosed within parentheses (that is, within brackets). The parameter belongs to the method alert() and note that it is enclosed with single quotation marks. Note that the whole statement for the onLoad event handler is enclosed with double quotation marks. When two sets of quotation marks are required, then one set must be double and the other set must be single quotation marks. Otherwise the browser will be unable to keep things straight. Omitting these quotation marks will result in an error message. Note that these quotation marks did not appear in the pop-up window.
  5. If you want the message to be displayed only when the visitor leaves your web page, use onUnload instead of onLoad. You can also change the message to suit your own needs.
  6. I would suggest that you take some time to "play" with this statement by SWITCHING to NOTEPAD or to a similar "text only" word processor, type in a HEAD, TITLE and then the BODY tag as in:

    <HTML>
    <HEAD>
    <TITLE>Java Fun</TITLE>
    </HEAD>
    <BODY onLoad="window.alert('I sure hope you bookmarked this website!')" BGCOLOR="#FFFFFF" TEXT="#000000">
    </BODY>
    </HTML>

    Save this HTML document using a suitable name such as alert.htm and then SWITCH back to your browser and load the document to see the results. If you made a typing or other error, SWITCH back to your word processor, correct the problem, save the corrected document and try again.

    Try also onUnload to see its effect and also try different length messages. You can learn a lot from experimenting so take your time and try a few different things.

Unfortunately, the JavaScript Alert window that appeared when you loaded this web page will appear every time you re-load or return to this page. This can be a nuisance for some people. Of course, you can do a test to see if a visitor is simply returning to a web page or if the visitor is there for the very first time. You can then adjust your introduction accordingly. For example, if the visitor is there for the first time, you may want to ask for a name and welcome him or her to your website. If it is a return visit, you may simply want to display a "welcome back" message along with the visitor's name. How this is all done is beyond the scope of this lesson.


top | | bottom |

THE CONFIRM AND PROMPT JAVASCRIPT WINDOWS

We will now study two other JavaScript windows and they are: Switch to your text only word processor and type in the following document (web page) exactly as shown. You can also copy and paste to save some typing by following these steps:
  1. Hold the mouse button down and drag the mouse cursor over the statements given below so that the statements become highlighted.
  2. Choose COPY from the EDIT menu.
  3. Switch to Notepad or similar text only word processor and choose PASTE from the EDIT menu. Your document will now be in your word processor.
  4. Save the document using a suitable file name and extension.
  5. Switch back to your browser and load the file
In this lesson, I will assume you are typing the document. I think there is some value in typing if there isn't too much to type. If you make typing errors, you get a chance to sharpen your editing skills in correcting these errors. However, the method you use is up to you. Now here is your first document. Please enter into your word processor:

<HTML>
<HEAD>
<TITLE>Java Fun</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide the JavaScript from older browsers
document.write(confirm("Do you like this website of HTML lessons?"))
document.write("<BR>")
document.write(prompt("Which lesson is your favorite?"))
// End hiding of script -->
</SCRIPT>

</BODY>
</HTML>

Now save this web page, switch to your browser, load the page to see what happens. This example illustrates how to include JavaScript code in with your HTML code.

In order to avoid too many interactive events on this page at one time, I have these two JavaScript windows on another page. Please click here to see these Confirm and Prompt windows and hopefully your results were exactly the same. When you have checked out the windows, return here for a discussion.

WELCOME BACK! Now here is your first problem:

Problem 1: a) When you click on OK in the JavaScript Confirm window, what does your browser echo back on the screen? That is, what does your browser immediately print on the screen?

b) When you typed in your answer to the question Which lesson is your favorite? and clicked on OK, what did your browser echo back on the screen?

Click here to go to the answer section |

Here is the web page again but with the lines numbered for discussion purposes.

Line 1: <HTML>
Line 2: <HEAD>
Line 3: <TITLE>Java Fun</TITLE>
Line 4: </HEAD>
Line 5: <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
Line 6:
Line 7: <SCRIPT LANGUAGE="JavaScript">
Line 8: <!-- Hide the JavaScript from older browsers
Line 9: document.write(confirm("Do you like this website of HTML lessons?"))
Line 10: document.write("<BR>")
Line 11: document.write(prompt("Which lesson is your favorite?"))
Line 12: // End hiding of script -->
Line 13: </SCRIPT>
Line 14:
Line 15: </BODY>
Line 16: </HTML>

Discussion:

  1. Lines 1 to 5 represent the usually main parts of a web page. The BODY tag in line 5 also sets up black text on a white background.
  2. Line 6 is a blank line only to set the JavaScript apart from the standard main parts of the web page. This blank line (as well as the blank line 14) can be omitted.
  3. Line 7 tells the browser that what follows is JavaScript code. JavaScript code must be contained within the SCRIPT element. Line 13 tells the browser that the JavaScript code has ended.
  4. In lines 9, 10 and 11, document is called an object and write() is a method of the document object. Obviously document.write tells the browser to write (or print) something. In lines 9 and 11, the two questions in the brackets are parameters that are passed to the method to be printed. Note also that document.write must be written in lower case letters.
  5. Confirm() (line 9) is a built-in function that opens a "Confirm window" and prints the question "Do you like this website of HTML lessons?". Confirm() and prompt(), like alert(), are methods of the window object. In JavaScript, the highest level object is the window object and so if the object name is missing from a statement, the window object is assumed. Thus line 9 could also be written as:

    document.write(window.confirm("Do you like this website of HTML lessons?"))

    The question asked in line 9 is a parameter for the method confirm() and must be contained within quotation marks and brackets. Note also that the argument for the write() method must also be contained within brackets (confirm("Do you like this website of HTML lessons?")).

  6. The ("<BR>") in line 10 ensures a line break between the two responses. This line illustrates that HTML code can also be used within JavaScript code. The quotation marks must be included around the <BR>. You may have noticed that the two responses according to your input were printed on separate lines. This was the result of the <BR> tag.
  7. Notice that the entire script was enclosed as a comment. Line 8 is the opening comment line which begins with <!-- and line 12 closes the comment with --> . The purpose for doing this is to hide the code from older browsers that cannot interpret JavaScript. The <!--   --> is the comment container for HTML. Thus the HTML comment container will hide the code from an older browser but will still allow the JavaScript to execute on a capable browser (and most browsers today can interact with JavaScript). If you don't do it this way, all the code will be displayed in older browsers as text on the screen. The // at the beginning of any line in a JavaScript program (see line 12) tells the browser that this is a comment line and not to be executed as JavaScript.

Problem 2: In the statement:

document.write(prompt("Which lesson is your favorite?"))

a) What is the document part called?
b) What is write() called?
c) What is prompt() called?
d) What is Which lesson is your favorite? called?

Click here to go to the answer section |

Problem 3: Switch back to your word processor and remove the document.write from lines 9 and 11 and also remove line 10 completely, so that the JavaScript part of the web page now looks like:

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide the JavaScript from older browsers
confirm("Do you like this website of HTML lessons?")
prompt("Which lesson is your favorite?")
// End hiding of script -->
</SCRIPT>

Save these changes, switch to your browser and load this changed document. What is the effect of removing the document.write part from the statements?

Click here to go to the answer section |

You can also include in this JavaScript code, the Alert window that you saw when this page was first loaded. The line to include is:

alert("I sure hope you bookmarked this website!")

as in:

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide the JavaScript from older browsers
alert("I sure hope you bookmarked this website!")
confirm("Do you like this website of HTML lessons?")
prompt("Which lesson is your favorite?")
// End hiding of script -->
</SCRIPT>


top | | bottom |

PERSONALIZING YOUR VISITOR'S NAME

Recall in our example introducing the Prompt window, when you typed an answer to the question, Which lesson is your favorite? and clicked OK, your answer was immediately echoed back on the screen. This really serves no useful purpose in an actual HTML document - so let's extend this example by asking only for the visitor's name and instead of having the name echoed back on the screen, have the browser print the name along with a nice comment. In other words, let's make the name interactive and personal.

First click here to see this situation in action and then return here to continue with the lesson.

WELCOME BACK! Here are the lines that produced the Prompt window, the name and message. Please switch to your word processor and enter the following lines:

<HTML>
<HEAD>
<TITLE>Java Fun</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">

<FONT COLOR="#FF00FF"><H2 ALIGN="center">
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide the script from older browsers

var YourName
YourName = window.prompt("Please enter your name:")

document.write("Thank you " + YourName + "<BR>" + "Welcome to my website!")

// End hiding of script -->
</SCRIPT>
</H2></FONT>

</BODY>
</HTML>

Now save this document, load it into your browser and hopefully your results will be the same as what you saw earlier. For discussion purposes, here is the document again with the lines numbered:

Line 1: <HTML>
Line 2: <HEAD>
Line 3: <TITLE>Java Fun</TITLE>
Line 4: </HEAD>
Line 5: <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
Line 6:
Line 7:<FONT COLOR="#FF00FF"><H2 ALIGN="center">
Line 8: <SCRIPT LANGUAGE="JavaScript">
Line 9: <!-- Hide the script from older browsers
Line 10:
Line 11: var YourName
Line 12: YourName = window.prompt("Please enter your name:")
Line 13:
Line 14: document.write("Thank you " + YourName + "<BR>" + "Welcome to my website!")
Line 15:
Line 16: // End hiding of script -->
Line 17: </SCRIPT>
Line 18: </H2></FONT>
Line 19:
Line 20: </BODY>
Line 21: </HTML>

Discussion:

  1. Line 6 is a blank line simply to separate the usual beginning elements from the body of the web page.
  2. Line 7 centers and colors the text using normal HTML coding. If your browser does not support the COLOR attribute for the FONT tag, then you won't be able to see the color. You can leave out the FONT tag if your browser does not support coloring portions or blocks of text.
  3. Line 12 sets up the Prompt dialog window and has the instruction "Please enter your name:" printed in it. Note in this line that whatever the visitor types for his or her name will be assigned to variable YourName. YourName is called a variable. Variables are used to store data. So with variable YourName, we are storing or assigning whatever name (or data) the visitor types in.
  4. If we are going to use a variable, it should be declared to be such and line 11 does this with var YourName (meaning that YourName is to be treated as a variable). Note that any variable used in your script must be introduced or declared before that variable is used (the variable is being used in line 12). It does not make sense to declare something to be a variable after it has been used.
  5. You can choose any legal name for the variable - as long as it is not a name reserved by JavaScript for another use. I have a complete list of reserved variables names in my book "Learn JavaScript All By Yourself!" (discussed in the "Conclusion" section at the end of this lesson).
  6. The word "window" in line 12 can be omitted since all methods will default to the window object if the object name is omitted. Thus line 12 could simply be written as:

    YourName = prompt("Please enter your name:")

  7. You can actually leave out line 11 and the script will still work. This is because JavaScript is a rather loose and tolerant language which is unlike C or Java. For this reason you can "get away" with certain things in JavaScript that you can't get away with in C and Java. This however, does not mean that we should not exercise good programming practice and OOP languages dictate that variables should be declared. In lesson 21, I stated that browsers are quite tolerant to the HTML they accept. However, we must still ensure good coding practices because otherwise the way a web page is displayed in any particular browser is dependent on the error recovery scheme utilized by that browser. Browsers are purposely designed to be tolerant in the HTML that they accept, but they are not meant to be a substitute for an HTML editor. The same could be said for JavaScript. We should be careful to do the best job that we can so that browsers can easily display the results.
  8. Once the visitor has entered a name and clicked on OK, line 14 prints out "Thank you", followed by the person's name (stored in variable YourName), followed by a line break (<BR>), followed by "Welcome to my website!". The plus signs join these individual parts together.
Problem 4: In the above script, line 14 is the document.write statement. Note that Thank you is enclosed within quotation marks. Thank you is called a string (think of it as a "string" of characters). Why is there a space between the word you and the closing quotation mark (as in: "Thank you ")?

Click here to go to the answer section |


top | | bottom |

INTERACTING WITH YOUR VISITOR'S COMPUTER CLOCK

Here is a little JavaScript program that gives a nice comment along with the current date and time. These items will be given through the use of another JavaScript built-in object. First here are the results.

Please switch to your word processor and enter the following lines that give this output.

<HTML>
<HEAD>
<TITLE>Java Fun</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">

<H3 ALIGN="center">
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide the JavaScript from older browsers
document.write("Hope you are having a great day!")
document.write("<BR>")
document.write("Today's date is ",Date())
// End hiding of script -->
</SCRIPT></H3>

</BODY>
</HTML>

Now save the document, switch back to your browser and load the file to see the results for yourself. For the discussion, here first is the web page again with line numbers added.

Line 1: <HTML>
Line 2: <HEAD>
Line 3: <TITLE>Java Fun</TITLE>
Line 4: </HEAD>
Line 5: <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
Line 6:
Line 7: <H3 ALIGN="center">
Line 8: <SCRIPT LANGUAGE="JavaScript">
Line 9: <!-- Hide the JavaScript from older browsers
Line 10: document.write("Hope you are having a great day!")
Line 11: document.write("<BR>")
Line 12: document.write("Today's date is ",Date())
Line 13: // End hiding of script -->
Line 14: </SCRIPT></H3>
Line 15:
Line 16: </BODY>
Line 17: </HTML>

Discussion:

  1. In line 10, the statement Hope you are having a great day! was printed within the JavaScript code. You can of course, have the statement printed outside the JavaScript code as regular HTML text as in:

    Hope you are having a great day!<BR>
    <SCRIPT LANGUAGE="JavaScript">
    <!-- Hide the JavaScript from older browsers
    document.write("Today's date is ",Date())
    // End hiding of script -->
    </SCRIPT>

  2. In line 12, the object Date() is all it takes to print the current date and time. Date() is a built-in function that displays all this information. It is called an object because it is made up of many methods (or parts) - such as the hour part, the minutes part, the day of week part, the year part, etc. Each of these parts is called a method of the object. Note that the empty brackets after "Date" (()) are necessary. It simply indicates to the browser that in this case there is no parameter for the Date object.
  3. The information in Date() itself comes from the internal clock in your visitor's computer and so the date will always be correct if the clock in your visitor's computer is correct (which we can assume it is).
Problem 5: Our date and time program above has three document.write statements (lines 10, 11 and 12) and here they are again:

document.write("Hope you are having a great day!")
document.write("<BR>")
document.write("Today's date is ",Date())

What single document.write statement will take the place of these three statements? In other words, replace the three document.write statements with one document.write statement.

Click here to go to the answer section |


Let's now make our date more interesting. Let's make a JavaScript program that checks the date function of the visitor's computer clock and then prints a message according to the time of day. What this JavaScript actually does is check to see if the time lies between midnight and 4 a.m. If this is the case, we will have the browser assume that the visitor is up late and will print the message "Goodness you're up late!". If the time is between 4 a.m. and 6 a.m. the browser will assume that the visitor is up early and will print the message "Wow! You're up early!". If the time is between 6 a.m. and 12 noon, the message will be simply "Good Morning!"; if the time is between 12 noon and 6 p.m., the message will be "Good Afternoon!"; and if the time is between 6 p.m. and midnight, the message will be "Good Evening!". Once the message has been printed, the browser will then print the date and time.

Here is the output for your current time of day:

Here are the lines that give this message and time. Please switch to your word processor and enter the following exactly as given. It may look complicated at first but a complete explanation follows the coding:

<HTML>
<HEAD>
<TITLE>Java Fun</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide the JavaScript from older browsers

document.write("<CENTER><FONT SIZE=+1 COLOR=blue>")

     today = new Date()

        if((today.getHours() >=0) && (today.getHours() <4))
{
document.write("Goodness you're up late!")
}

        if((today.getHours() >=4) && (today.getHours() <6))
{
document.write("Wow! You're up early!")
}

        if((today.getHours() >=6) && (today.getHours() <12))
{
document.write("Good Morning!")
}

        if((today.getHours() >=12) && (today.getHours() <18))
{
document.write("Good Afternoon!")
}

        if((today.getHours() >=18) && (today.getHours() <=24))
{
document.write("Good Evening!")
}

document.write("<BR>")
document.write("Today's date is ",Date())
document.write("</FONT></CENTER>")
// End hiding of script -->
</SCRIPT>

</BODY>
</HTML>

Now save this document, switch back to your browser, load the document and the output should be the same as that given above. For the discussion, here is the web page again with numbered lines:

Line 1: <HTML>
Line 2: <HEAD>
Line 3: <TITLE>Java Fun</TITLE>
Line 4: </HEAD>
Line 5: <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
Line 6:
Line 7: <SCRIPT LANGUAGE="JavaScript">
Line 8: <!-- Hide the JavaScript from older browsers
Line 9:
Line 10: document.write("<CENTER><FONT SIZE=+1 COLOR=blue>")
Line 11:
Line 12:      today = new Date()
Line 13:
Line 14:         if((today.getHours() >=0) && (today.getHours() <4))
Line 15: {
Line 16: document.write("Goodness you're up late!")
Line 17: }
Line 18:
Line 19:         if((today.getHours() >=4) && (today.getHours() <6))
Line 20: {
Line 21: document.write("Wow! You're up early!")
Line 22: }
Line 23:
Line 24:         if((today.getHours() >=6) && (today.getHours() <12))
Line 25: {
Line 26: document.write("Good Morning!")
Line 27: }
Line 28:
Line 29:         if((today.getHours() >=12) && (today.getHours() <18))
Line 30: {
Line 31: document.write("Good Afternoon!")
Line 32: }
Line 33:
Line 34:         if((today.getHours() >=18) && (today.getHours() <=24))
Line 35: {
Line 36: document.write("Good Evening!")
Line 37: }
Line 38:
Line 39: document.write("<BR>")
Line 40: document.write("Today's date is ",Date())
Line 41: document.write("</FONT></CENTER>")
Line 42: // End hiding of script -->
Line 43: </SCRIPT>
Line 44:
Line 45: </BODY>
Line 46: </HTML>

Discussion:

  1. Some of the lines are blank and others are indented. This is very common with OOP languages. Blank lines separate sections of script and indented lines make the script much easier to read and can indicate what belongs together.
  2. Line 10 centers the text and clock and prints the text one font size larger than the surrounding text size. Note that these are HTML tags contained within quotation marks. Blue is defined to be the color for the text and for the date and time.
  3. Line 41 near the end of the script cancels the increased font size, the blue color and the centering of text.
  4. Line 12 transfers all the information in object Date() to variable today. Since Date() contains several methods such as hour, minutes, date, year, etc. so today will also contain these same methods and that is why today must also be thought of as an object. The word "new" must be there. You will get an error message without it. You can think of new Date() as telling the browser to "take a new instance of the date" or to "take a new reading of the date".
  5. You can use any legal variable name for the object (that is, any name not reserved by JavaScript). I chose the name "today" but you are free to choose some other name.
  6. In today.getHours() (line 14), the browser will extract the hour from the object today. .getHours() is a called a method of the object today. Some of the other methods that can be extracted are .getMinutes(), .getMonth(), .getDate(), .getYear(), etc.
  7. Also with line 14, the browser begins a series of checks on the hour of the date stored in object today in order to determine what comment to write. These checks are done in lines 14, 19, 24, 29 and 34. The browser does these checks by making use of conditional statements. Conditional statements are if statements. The browser will check each conditional statement to determine if it is true or if it is false. Conditional statements are often called If ... then statements meaning "If the condition is true, then do this". Because the browser will check each of the five conditions in our program, one at a time, we need to be very specific in our conditions. Here is how it all works:

    The first condition is in line 14 and it has the browser check to see if the hour part of the date lies between 0 AND 4 meaning between midnight and 4 a.m. If the condition is true then the message "Goodness you're up late!" is printed (line 16). Note that the comment is surrounded by brace brackets { }. Brace brackets are discussed below.

    If the condition is false, that is, the time is not between 0 and 4 a.m., then the browser does not execute the document.write statement in line 16 and instead drops down to line 19 which is the next condition to be checked.

    The second condition is in line 19 and here the browser checks to see if the time is between 4 and 6 in the morning. If the answer is true, "Wow! You're up early!" is printed. If the condition is false this message is not printed. Each condition is checked in this manner. After all the conditions have been checked, the browser will be at line 39.

  8. Once a message (such as "Good Morning") has been printed, we need a line break so that the date and time will be printed on a new line. Line 39 forces this needed line break.
  9. Line 40 prints the complete date and time.
  10. As this is a 24 hour clock, the statement in line 29 which is:

    if((today.getHours() >=12) && (today.getHours() <18))

    will check for the time between 12 noon and 6 p.m. (12+6=18).

  11. Note in the conditional statements that && is the symbol for AND (see line 14 for example). AND is called a logical operator. The logical operator AND means that BOTH stated conditions must be true. Another logical operator is OR written in JavaScript as ||. You would use OR if you only want one of the two conditions to be true. To specify the AND and OR Logical Operators, you require two of the same symbol. That is why you see && for AND and two vertical lines (||) for OR.

    The equal sign is not a logical operator. It is a comparison operator because you use it to compare things. If you are using the equal sign to compare two things, you need two equal signs in a row (==). For example, if you want to check specifically if the hour was equal to exactly 7, then the statement would have to be:

    if(today.getHours() == 7)

    Note in line 12, today = new Date(), has only one equal sign. This is because "=" in this case is NOT read as "today is equal to new Date". It is read as: assign the object "new Date()" to the variable "today". We are not doing any comparing here. That is, in this line 12, "=" represents an assignment and not "compares to" (or "equals to"). Thus you use one equal sign for assignment and two equal signs for comparison.

  12. Spacing around symbols is optional. Thus "today.getHours() >=12" could also be written as "today.getHours()>=12" or as "today.getHours() >= 12". It is a personal preference.
  13. The { } are called brace brackets. For each opening brace bracket, {, there must be a closing brace bracket, }. Brace brackets are used to enclose codes that belong together. Since we only have one line of code after each "if" statement, we really did not need to use brace brackets. However, Java, C and other OOP languages do require them, and possibly for consistency, brace brackets are also usually included with JavaScript. So the opening brace bracket indicates that a group of related lines are beginning and a closing brace bracket indicates that the grouping has ended. Brace brackets are often found on lines by themselves so that they clearly indicate the beginning and ending of a group of related coding statements. However, this does not have to be the case.

    Brace brackets can also be nested, that is, you can have brace brackets inside of brace brackets. If you plan to use nested brace brackets, then the last one opened must be the first one closed (in the same way that the last HTML tag opened must be the first one closed).

Problem 6: There are also other methods involving the Date object. For example, we already know that .getHours() will only look at the hour part of the time. What do you think each of the following methods involve?
a) .getMonth()
b) .getYear()
c) .getDate()

Click here to go to the answer section |

Problem 7: The function .getMonth is always out by one month. For example, March is interpreted as the second month and not as the third month. The reason for this is because arrays start at zero (0) and so January is considered to be month number zero. For this reason you need to add +1 to the month so that January, for example, will be interpreted as 1 representing the first month. Now having said this, what do you think the browser will print on the screen with the following line?

document.write("It is now "+(today.getMonth()+1)+"/"+today.getDate()+"/"+today.getYear())

Click here to go to the answer section |


top | | bottom |

CONCLUSION - WANT MORE JAVASCRIPT?

This lesson is only intended to give you a brief introduction to JavaScript. JavaScript can certainly add some interesting interactions with your visitors. Yet there is so much more to learn - things like scrolling text, controlling the Status Bar at the bottom of the browser, having fun with colors, animation, functions, looping, random numbers and so on. I cover all these topics and so much more in my book, "Learn JavaScript All By Yourself!" which can be downloaded right into your computer.

For example, you know that in HTML, you can only set the background color of a web page once. Now with JavaScript you can change the background color as many times as you like on a page! To see this, just click on the following buttons.








This is just a sampling of nearly 150 beautiful built-in JavaScript colors that you will learn to code in different ways! JavaScript can certainly spruce up your web pages and make them come alive. If you have been able to learn HTML, then you can also learn JavaScript. It's really an easy language to learn!

If you are interested in a book of JavaScript lessons written in the same easy interactive style and layout as this website of HTML lessons, then I would like to recommend my book, "Learn JavaScript All By Yourself!"

This series of JavaScript lessons is available for downloading as one zipped file for only $14.95 U.S. and you can pay by Visa or Mastercard.

You can study these JavaScript lessons in your browser off-line or you can print them out on paper. If you were to print out these lessons on standard letter size paper with 1 inch margins using Times New Roman with a normal font size of 12, you would have over 200 pages!

Learn JavaScript All By Yourself!" begins with the assumption that you know nothing about JavaScript. We will go a lot slower with the lessons in the book and with lots of explanations and examples (we packed a lot of stuff in this Lesson 23).

These JavaScript lessons are the culmination of my efforts to produce the best possible self-learning course on JavaScript available today - a course that assumes no prior knowledge of JavaScript. Please click here if you would like more information or to place an order.

Here is an e-mail I received from a Matthew Young. I have never met Matthew and I do not know who he is, but I do want to thank him for the following which is reprinted with permission:

Thank you for sending me your tutorial "Learn JavaScript All By Youself". I was very impressed with the efficiency with which my order was processed and the simplicity of the entire procedure.

I must admit that I felt like a kid on Christmas Eve awaiting your "book". During the week prior to receiving your tutorial I visited over 30 other JavaScript sites. Although I made some wonderful discoveries and learnt much, none of these sites came even close to satisfying my hunger for a clear and concise account of the why's and how's of JavaScript. I have been fairly busy this week and have only made it through the first three lessons of your book; however, I learnt more in the first three paragraphs of it than I had whilst browsing through whole pages of some other sites!

I must congratulate you on the way you make everything seem so simple and straightforward (yet without simplifying the material). Best of all, I am finding your lessons to be great FUN. I am hoping that I can transform my site into something truly special - and something that will always be a reflection upon your own work.

Thanks again.

Sincerely,

Matthew Young

Again, if you would like more information or to place an order, just click here.


top | | bottom |

ANSWERS TO THE PROBLEMS POSED IN THIS LESSON

  1. a) The answer depends on the browser your are using. In Netscape, the browser prints the word true on the screen. In Internet Explorer, the browser prints the number -1. Normally these values would be used in a script to check a visitor's input to see what response they gave. If you click on "Cancel" instead of on "OK", a Netscape browser will print false while an Explorer browser will print the number 0.
    b) The browser printed whatever you typed in the Prompt window.
  2. a) Document is called an object.
    b) Write() is called a method of the document object.
    c) Prompt() is called the argument for the method "write". Prompt() is also a method of the window object.
    d) "Which lesson is your favorite?" is called the parameter for the prompt() method (and this parameter is passed on to the write() method to be printed).
  3. The input was not echoed back on the screen.
  4. The space is needed to ensure a space between Thank you and the visitors name (store in variable YourName). For example, if the visitor's name was John, the line will read Thank you John instead of Thank youJohn.
  5. document.write("Hope you are having a great day!" + "<BR>" + "Today's date is ",Date())
  6. a) .getMonth() has the browser look only at the month
    b) .getYear() has the browser look only at the year
    c) .getDate() has the browser look only at the day
  7. The browser will print: It is now month/day/year as in:  

| Back to the top of the page |

Return to Home Page | | Return to Alternate Home Page | | Send me to Lesson Twenty-Four |