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. 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. 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.
WHY LEARN JAVASCRIPT?
When you finish this first part, 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 first part will give you a taste of the fun you can have with JavaScript
on your web pages - so let's get started with the first example.
THE CONFIRM AND PROMPT JAVASCRIPT WINDOWS
Let's look at two JavaScript windows:
the Confirm Window and
the Prompt Window
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 these 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.
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 these 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 these 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 these 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 1: 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?
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 these HTML lessons?")
prompt("Which lesson is your favorite?")
// End hiding of script -->
</SCRIPT>
Problem 2: 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?
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.
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 3: 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 ")?
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.
Hope you are having a great day!
Today's date is Tue Jun 19 14:38:43 GMT-0400 (Eastern Daylight Time) 2001
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).
The 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())
Problem 4: 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 the 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:
Good Afternoon!
Today's date is Tue Jun 19 14:38:43 GMT-0400 (Eastern Daylight Time) 2001
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 5: 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()
Problem 6: 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())
CONCLUSION - WANT MORE JAVASCRIPT?
This lecture 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.
Here is an example of what can be done in JAVAScript. 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 can 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!
ANSWERS TO THE PROBLEMS POSED IN THIS LECTURE
1.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).
2.The input was not echoed back on the screen.
3.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.
4.document.write("Hope you are having a great day!" + "<BR>"
+ "Today's date is ",Date())
5.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
6.The browser will print: It is now month/day as in:
It is now 6/19
JavaScript is a scripting language developed by Netscape. JavaScript works in all major browsers that are version 3.0 or higher.
What is JavaScript?
JavaScript is a scripting language
A scripting language is a lightweight programming language
A JavaScript is lines of executable computer code
A JavaScript can be inserted into a HTML page
JavaScript is an open scripting language that anyone can use
without purchasing a license
JavaScript is supported by all major browsers like Netscape
and Internet Explorer
How Does it Work?
When a JavaScript is inserted into an HTML document, the Internet browser will read the HTML and interpret the JavaScript. The JavaScript can be executed immediately, or at a later event.
What can a JavaScript Do?
JavaScript gives HTML designers a programming tool
HTML authors are normally not programmers, but since JavaScript is a very light programming language with a very simple syntax, almost anyone can start putting small "snippets" of code into their HTML documents.
JavaScript can put dynamic text into an HTML page
A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into the display of an HTML page, just like the static HTML text: <h1>Bill Gates</h1> does.
JavaScript can react to events
A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element.
JavaScript can read and write HTML elements
A JavaScript can read an HTML element and change the content of an HTML element.
JavaScript can be used to validate data
JavaScripts can be used to validate data in a form before it is submitted to a server. This function is particularly well suited to save the server from extra processing.
JavaScript Joke
Customer: "My browser gives me a JavaScript error. Is JavaScript a
dangerous virus?"
JavaScript How To ...
Use the <script> tag to insert a JavaScript in an HTML document.
Examples
Write
text
How to write text on a page
Write
text with formatting
How to format the text on your page with HTML tags
How to Put a JavaScript Into an HTML Document
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
And it produces this output:
Hello World!
To insert a script in an HTML document, use the <script> tag. Use the type attribute to define the scripting language.
<script type="text/javascript">
Then comes the JavaScript: In JavaScript the command for writing some text on a page is document.write:
document.write("Hello World!")
The script ends:
</script>
Ending Statements with a Semicolon?
With the traditional programming languages C++ and Java, each code statement has to end with a semicolon.
Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional and are required only if you want to put more than one statement on a single line.
How to Handle Older Browsers
Older browsers that do not support scripts will display the script as page content. To prevent them from doing this, you can use the HTML comment tag:
<script type="text/javascript">
<!--
some statements
//-->
</script>
The two forward slashes in front of the end of comment line (//) are a JavaScript comment symbol, and prevent the JavaScript from trying to compile the line.
Note that you can't put // in front of the first comment line (like //<!--), because older browser will display it. Funny? Yes ! But that's the way it is.
JavaScript Where To ...
Scripts in a page will be executed immediately when the page loads. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
Examples
Head
section
Scripts that contain functions go in the head section of the document.
Then we can be sure that the script is loaded before the function is
called.
Body
section
Execute a script that is placed in the body section.
External
script
How to access an external script.
Where to Put the JavaScript
Scripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
<html>
<head>
<script type="text/javascript">
some statements
</script>
</head>
Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.
<html>
<head>
</head>
<body>
<script type="text/javascript">
some statements
</script>
</body>
Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.
<html>
<head>
<script type="text/javascript">
some statements
</script>
</head>
<body>
<script type="text/javascript">
some statements
</script>
</body>
How to Run an External JavaScript
Sometimes you might want to run the same script on several pages, without writing the script on each and every page. To simplify this you can write a script in an external file, and save it with a .js file extension, like this:
document.write("This script is external")
Save the external file as xxx.js
-The filename can not contain more than 8 letters
-The external script cannot contain the <script> tag
Now you can call this script, using the "src" attribute, from any of your pages:
<html>
<head>
</head>
<body>
<script src="xxx.js">
</script>
</body>
</html>
Remember to place the script exactly where you normally would write the script.
JavaScript Variables
A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value.
Examples
Variable
Variables are used to store data. This example will show you how.
Rules for Variable names:
Declare a Variable
You can create a variable with the var statement:
var strname = some value
You can also create a variable without the var statement:
strname = some value
Assign a Value to a Variable
You assign a value to a variable like this:
var strname = "Hege"
Or like this:
strname = "Hege"
The variable name is on the left side of the expression and the value
you want to assign to the variable is on the right. Now the variable "strname"
has the value "Hege".
Lifetime of Variables
When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
JavaScript Operators
Operators are used to operate on values.
String Operator
A string is most often a text, for example "Hello World!". To stick two or more string variables together, use the + operator.
txt1="What a very"
txt2="nice day!"
txt3=txt1+txt2
The variable txt3 now contains "What a verynice day!".
To add a space between two string variables, insert a space into the expression, OR in one of the strings.
txt1="What a very"
txt2="nice day!"
txt3=txt1+" "+txt2
or
txt1="What a very "
txt2="nice day!"
txt3=txt1+txt2
The variable txt3 now contains "What a very nice day!".
Comparison Operators
Operator
Description
Example
==
is equal to
5==8 returns false
!=
is not equal
5!=8 returns true
>
is greater than
5>8 returns false
<
is less than
5<8 returns true
>=
is greater than or equal to
5>=8 returns false
<=
is less than or equal to
5<=8 returns true
Arithmetic Operators
Operator Description
Example
Result
+
Addition
2+2
4
-
Subtraction
5-2
3
*
Multiplication
4*5
20
/
Division
15/5
3
5/2
2.5
%
Modulus. Returns the
remainder after the first
division
Example 1:
5%2
1
5/2 results in 2, remainder 1
Example 2:
10%8
2
10/8 results in 1, remainder 2
++
Increment
x=5
x++
x=6
--
Decrement
x=5
x--
x=4
Assignment Shorthand Operators
Operator Example
Is The Same As
+=
x+=y
x=x+y
-=
x-=y
x=x-y
*=
x*=y
x=x*y
/=
x/=y
x=x/y
%=
x%=y
x=x%y
Logical Operators
Operator
Description
Example
&&
and
x=6
y=3
(x < 10 && y > 1) returns
true
||
or
x=6
y=3
(x==5 || y==5) returns false
!
not
x=6
y=3
x != y returns true
JavaScript Functions
A function is a reusable code-block that will be executed by an event, or when the function is called.
Examples
Function
How to call a function.
Function
with arguments
How to pass a variable to a function, and use the variable value in the
function.
Function
with arguments 2
How to pass variables to a function, and use these variable values in
the function.
Function
that returns a value
How to let the function return a value.
A
function with arguments, that returns a value
How to let the function find the sum of 2 arguments and return the
result.
A function contains some code that will be executed by an event or a call to that function. A function is a set of statements. You can reuse functions within the same script, or in other documents. You define functions at the beginning of a file (in the head section), and call them later in the document. It is now time to take a lesson about the alert-box:
This is JavaScript's method to alert the user.
alert("here goes the message")
How to Define a Function
To create a function you define its name, any values ("arguments"), and some statements:
function myfunction(argument1,argument2,etc)
{
some statements
}
A function with no arguments must include the parentheses:
function myfunction()
{
some statements
}
Arguments are variables that will be used in the function. The variable values will be the values passed on by the function call.
By placing functions in the head section of the document, you make sure that all the code in the function has been loaded before the function is called.
Some functions return a value to the calling expression
function result(a,b)
{
c=a+b
return c
}
How to Call a Function
A function is not executed before it is called. You can call a function containing arguments:
myfunction(argument1,argument2,etc)
or without arguments:
myfunction()
The return Statement
Functions that will return a result must use the "return" statement. This statement specifies the value which will be returned to where the function was called from. Say you have a function that returns the sum of two numbers:
function total(a,b)
{
result=a+b
return result
}
When you call this function you must send two arguments with it:
sum=total(2,3)
The variable sum has the value 5.
JavaScript Conditional Statements
Conditional statements in JavaScript are used to perform different actions based on different conditions.
Examples
If
statement
How to write an If statement. Use the if statement if you want a set of
code to be executed if a specified condition is true
If...else
statement
How to write an If...Else statement. Use the If...Else statement if you
want one set of code to be executed if the condition is true and
another set of code to be executed if the condition is false
Random
link
This example demonstrates a link, when you click on the link it will take
you to W3Schools.com OR to W3AppML.com. There is a 50%
chance for each of them.
Switch
statement
How to write a switch statement. Use this statement if you want to
select one of many blocks of code to execute
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In JavaScript we have two conditional statements:
IF Condition
You should use the IF statement if you want to execute some code if a condition is true, or if you want to select one of two blocks of code to be executed.
If you want to execute only one statement when a condition is true, use this syntax for the if...else statement, like this:
if (condition)
{
code to be executed if condition is true
}
Notice that there is no ..else.. in this syntax. You just tell the code to perform one action if the condition is true.
If you want to execute some statements if a condition is true and execute others if a condition is false, use this syntax for the if....else statement, like this:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
Switch Condition
You should use the Switch statement if you want to select one of many blocks of code to be executed.
switch (expression)
{
case label1:
code to be executed if expression = label1
break
case label2:
code to be executed if expression = label2
break
default:
code to be executed
if expression is different
from both label1 and label2
}
This is how it works: First we have a single expression (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear "
If the variable visitor is equal to PRES, then put the string "Dear
President " in the variable named greeting. If the variable visitor is
not equal to PRES, then put the string "Dear " into the variable named
greeting.
JavaScript Looping
Looping statements in JavaScript are used to execute the same block of code a specified number of times.
Examples
For
loop
How to write a For loop. Use a For loop to run the same block of code
a specified number of times
Looping
through HTML headers
How to use the For loop to write the HTML headers.
While
loop
How to write a While loop. Use a While loop to run the same block of
code while or until a condition is true
Do
while loop
How to write a Do While loop. Use a Do While loop to run the same
block of code while or until a condition is true. This loop will always
be
executed once, even if the condition is false, because the statements
are executed before the condition is tested
Looping
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to do this. In JavaScript we have the following looping statements:
The while statement will execute a block of code while a condition is true..
while (condition)
{
code to be executed
}
do...while
The do...while statement will execute a block of code once, and then it will repeat the loop while a condition is true
do
{
code to be executed
}
while (condition)
for
The for statement will execute a block of code a specified number of times
for (initialization; condition; increment)
{
code to be executed
}
JavaScript Guidelines
Some things to know about JavaScript.
JavaScript is Case Sensitive
A function named "myfunction" is not the same as "myFunction". Therefore watch your capitalization when you create or call variables, objects and functions.
Symbols
Open symbols, like ( { [ " ', must have a matching closing symbol, like ' " ] } ).
White Space
JavaScript ignores extra spaces. You can add white space to your script to make it more readable. These two lines mean exactly the same:
name="Hege"
name = "Hege"
Break up a Code Line
You can break up a code line within a text with a backslash. The example below will be displayed properly:
document.write("Hello \
World!")
Note: You can not break up a code line like this:
document.write \
("Hello World!")
The example above will cause an error.
Insert Special Characters
You can insert special characters (like " ' ; &) with the backslash:
document.write ("You \& I sing \"Happy Birthday\".")
The example above will produce this output:
You & I sing "Happy Birthday".
Comments
You can add a comment to your JavaScript code starting the comment with "'//":
sum=a + b //calculating the sum
You can also add a comment to the JavaScript code, starting the comment with "/*" and ending it with "*/"
sum=a + b /*calculating the sum*/
Using "/*" and "*/" is the only way to create a multi-line comment:
/* This is a comment
block. It contains
several lines*/
Open up this JAVAScript Examples
page to access several coding examples.