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.
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.
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.
<BODY onLoad="window.alert('I sure hope you bookmarked this website!')" BGCOLOR="#FFFFFF" TEXT="#000000">
Note the following points:
<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.
<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?
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:
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.
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?
<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?
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>
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:
YourName = prompt("Please enter your name:")
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:
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>
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.
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:
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.
if((today.getHours() >=12) && (today.getHours() <18))
will check for the time between 12 noon and 6 p.m. (12+6=18).
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.
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()
document.write("It is now "+(today.getMonth()+1)+"/"+today.getDate())
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.
Congratulations on completing this series of 21 lessons. We also have more HTML
lessons available.