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.
<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>
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, 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?
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 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?")).
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 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:
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.
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 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.
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()+"/"+today.getYear())
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.