LESSON TWENTY-ONE
FUN WITH JAVASCRIPT


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

Return to Home Page | | Before we get started on Javascript | | 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? |


BEFORE WE GET STARTED ON JAVASCRIPT

This section applies to Internet Explorer browser users. When you try to load this lesson with newer versions of Internet Explorer, the following information bar pops up at the top of the browser window:

To help protect your security, Internet Explorer has restricted this webpage from running scripts or Active X controls that could access your computer. Click here for options.

When you click for the options, you are given three options:

Allow Blocked Content
What's the Risk
More information

You will always get this warning when you open Internet Explorer and then open a web page that contains a script such as a JavaScript. Please rest assured that not one JavaScript in this lesson or in my JavaScript course can harm your computer. I take great pride in these lessons and they are completely safe. There is nothing hidden in them. There are no security issues with any of these JavaScripts. I am in the business to help people, to teach people and not to cause any harm. If you want to do this JavaScript lesson, you must to click on Allow Blocked Content. You then receive an Alert window like the following:

You must click on Yes in order to do these lessons. Once you click on Yes, you will not be asked again as long as Internet Explorer remains open. If you close Internet Explorer and then later open it again, you will have to go through the above procedure again.


JAVA VERSUS JAVASCRIPT

Both Java and JavaScript are programming languages also known as scripting languages. They are also both examples of modern Object Oriented Programming (OOP) Languages. They both share a similar syntax and at first glance appear to be the same. However, there are some 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. 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. Finally, to do any programming in Java or to test applets, you need a Java Developers Kit (which you can get from the above Sun Microsystems website).

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.

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 much easier to write and much easier to learn.

So you can see that in many ways JavaScript and Java are two different languages and 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.

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 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 into your browser? If you did not see any pop-up window after this page was loaded, then it is possible that JavaScript has not been enabled in your browser. That is, your browser has the JavaScript turned off. This may be the case if you are using a very old version of Internet Explorer or Netscape Navigator. Versions from Netscape 4.0 and Explorer 4.0 and Firefox should already have their JavaScripts enabled.

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 an opening and closing bracket (in case it is hard to read).
  4. The message is called an argument and arguments must always be enclosed within parentheses (that is, within brackets). The argument 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 editor, 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>

    Note: The onLoad attribute of the BODY tag (onLoad="window.alert('I sure hope you bookmarked this website!')") must be printed on one line in Notepad or in whatever text editor you are using. A browser looks for the closing quotation marks on the same line as the opening quotation marks. If the closing quotation marks are on a different line, you have a JavaScript error and the script will not work. Therefore make sure that onLoad="window.alert('I sure hope you bookmarked this website!')" appears all on the same line in your text editor such as Notepad.

    Now 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 Notepad or to another text editor and enter the following document 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 your text editor such as Notepad and choose PASTE from the EDIT menu. Your document will now be in your text editor.
  4. Save the document using a suitable file name and extension (such as JavaFun.htm).
  5. Switch back to your browser and load the file.
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 text editor:

<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 (for example, JavaFun.htm), then 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. 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 clicked on OK in the Confirm window, what did your browser echo back on the screen? That is, what did your browser immediately print on the screen?
b) When you clicked on Cancel in the Confirm window, what did your browser echo back on the screen?
c) 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?
d) When you clicked on Cancel in the Prompt window, what was echoed 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 usual 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 arguments that are passed to the write() 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 the argument 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?")).

    Finally, for the reasons discussed earlier, line 9 must be written on one line in your text editor. The same also applies to line 11.

  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.
  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 course "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. Browsers generally 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 Date() object. Note that the empty brackets after "Date", (), are necessary. It simply indicates to the browser that in this case there is no argument 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 text editor 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 like 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() and .getYear().
  7. In 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. Thus the part in the brace brackets will only be executed if the condition is true.

    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 can also be used to check the time. For example, if you want to check specifically if the hour was equal to 7, then the statement would have to be:

    if(today.getHours() == 7)

    In this case, the equal sign is not called a logical operator. It is a called a comparison operator because you are using it to compare things. If you are using the equal sign to compare two things, you need two equal signs in a row (==).

    Note in line 12, today = new Date(), has only one equal sign. This is because we are not comparing anything (there is no if statement involved). In this line, the equal sign is read as: assign the object "new Date()" to the variable "today". That is, in this line 12, "=" represents an assignment and not a comparison. 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())

Click here to go to the answer section |


top | | bottom |

CONCLUSION - WANT MORE JAVASCRIPT?

This lesson gives you a brief introduction to JavaScript. JavaScript can certainly add some interesting interactions with your visitors. Yet there is so much more to learn - like creating your own personalized digital clock to display on your web page, scrolling text in a box or scrolling a message on the Status Bar at the bottom of the browser screen, having fun with colors, animations, functions, looping, random numbers, and so on. I cover all these topics and many more topics in my course, "Learn JavaScript All By Yourself!" which can be downloaded right into your computer.

Here is an example we will study early in the course. 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 color names.








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 an interactive series 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 course, "Learn JavaScript All By Yourself!"

This series of 14 JavaScript lessons of over 300 pages is available for downloading as one zipped file and now also includes four lessons on Dynamic HTML (DHTML).

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 21).

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.


top | | bottom |

ANSWERS TO THE PROBLEMS POSED IN THIS LESSON

  1. a) The answer depends on the browser you are using. In Firefox, Netscape and in Internet Explorer 4.0 and later versions, the browser prints the word true on the screen. In older Explorer versions, the browser prints the number -1.
    b) If you are using Firefox, Netscape and Explorer 4.0 and later versions, clicking on Cancel will generate the word false. Older Explorer browsers will generate the number 0. Normally these values would be used in a script to check a visitor's input to see what response was given and then another script would be executed depending on the response.
    c) The browser printed whatever you typed in the Prompt window.
    d) In Firefox, Netscape and Explorer 4.0 and later versions, the word "null" was echoed back on the screen. In older Explorer versions, nothing was printed on the screen.
    So here we have Firefox, Netscape and Internet Explorer 4.0 and later browsers showing the same results.
  2. a) Document is called an object.
    b) Write() is called a method of the document object.
    c) Prompt() is a method of the window object.
    d) "Which lesson is your favorite?" is called the argument for the prompt() method (and this argument 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 as in:  


Congratulations on completing this series of 21 lessons. We also have more HTML lessons available.


| Back to the top of the page |

Return to Home Page | | Return to Alternate Home Page |


The information contained in these free 21 lessons is Copyright ©, Brantford Educational Services, 1997 - 2012 by local and international copyright laws. All rights reserved. It is therefore illegal to copy these lessons into another website. If you find a copyright violation, please report it to email