Introduction to Javascript
Static versus dynamic web pages
Basic HTML allows us to prepare the appearance of a static web page. if
we want to display dynamic data, or want the layout and content of the
page to respond to user events dynamically, then additional features are
needed in the web page more than basic HTML
Approaches to provide this include :
- Client-side
- dynamic HTML (DHTML)
- Java Applets
- Javascript
- VBScript (IIS Only)
- Flash
- Server-side
- PHP
- CGI Scripts written in Perl, C, C++ or essentially any
language that exists on the server
- Java Servlettes
All of these break down into two types: 1) Server-side and 2)
Client-side programs. The server-side programs run on the web server
and the results of the programming running are sent to your browser on
your local machine. Client side programs are sent to your machine by
the web server and run on your local machine.
Server side programs require the input to be transmitted from the
client to the server and then the output or results transmitted back
to the client. This increases network traffic. The server also has to
do the calculations - thus increasing the load on the server.
Client-side programs eliminate this - the program is sent to the client
and then all the work and data input and output is done on the client.
Client-side pros and cons
- Client does the work - pro and con - does the client know how,
does it have the horsepower
- Program must be sent to the client - some programs can be large
Server-side pros and cons
- Server does the work - pro and con - we know the server knows
how, but can it handle the load
- Input and output must be sent back and forth - con
Development of Java and Javascript -
Note Javascript is not Java.
- Java is compiled to byte code and executed by the JVM
- Javascript is interpreted by the web browser directly
JavaScript - Strengths
- quick development
- no compilation
- interface features such as dialog boxes handled by the browser
and HTML code
- easy to learn
- doesn't share the more complex syntax of Java
- platform independence
- small overhead
JavaScript - Weaknesses
- limited range of built-in methods (functions)
- might change with next release
- no code hiding
- JavaScript visible within the HTML
- consensus is that JavaScripts are freeware
- lack of debugging and development tools
JavaScript and HTML
HTML tags
<SCRIPT> , </SCRIPT> contain the JavaScript portion within
the HTML document
<SCRIPT LANGUAGE="JavaScript">
JavaScript program goes here
</SCRIPT>
Hiding scripts from browsers that do not support JavaScript
<SCRIPT
LANGUAGE="JavaScript">
<!-- Hide the Script from other browsers
JavaScript program
// Stop hiding from other browsers -->
</SCRIPT>
Where to place the JavaScript code ?
JavaScript programs can be included anywhere in the header or body of
an HTML file but the preferred location is in the header just after the
</TITLE> tag. Long and complex scripts can be placed in a separate
file (must have a .js file extension) - Some browsers support this.
Test it.
<SCRIPT LANGUAGE="JavaScript"
SRC="http://www.you.com/JavaScript.js">
Example:
<HTML>
<head>
<TITLE>JavaScript Sample </TITLE>
</HEAD>
<BODY>
Here's a sample JavaScript:
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from other browsers
// Display a message
document.writeln("Have a nice day!<BR>");
// Stop hiding from other browsers -->
</SCRIPT>
</BODY></HTML>
Javascript language syntax.
- Syntax rule #1 in Javascript: All Javascript statements end with
a semicolon.
- Syntax rule #2 in Javascript: Comments begin with a double / and
continue to the end of the line.
- Syntax rule #2 in Javascript: Javascript keywords (like document,
writeln) are in lowercase.
- document.writeln("Hello"); this JavaScript statement
invokes the method writeln(), which is part of the document object
- in JavaScript, as in Java, everything is case-sensitive.
- document.writeln("Hello<BR>");
outputs the text Hello<BR> to the browser which interprets it as
HTML information
writeln is one of many methods or functions associated with the object
document
- in JavaScript, methods are called by combining the object name
with the method-name using a ".".
- Data that the method needs to perform is provided as an argument
in the parentheses
document.write("Welcome
!");
document.writeln("Have a great
day!");
The "write" sends the text on the current line in the browser. The
"writeln" sends the text on a new line in the browser. The SCRIPT
container does not affect the HTML structures where it occurs, so any
format tags or elements in the HTML file will affect the text produced
by write()
<HTML><HEAD>
<TITLE>JavaScript Sample </TITLE>
</HEAD>
<BODY>
Here's a sample JavaScript <B>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from other browsers
// Display a message
document.writeln("This is in bold.</B>");
// Stop hiding from other browsers -->
</SCRIPT>
</BODY></HTML>
Interacting with the user
The simplest way is with the prompt() method. Prompt displays the first
argument as the prompt text, the second argument is displayed as the
default value within the dialog box.
<SCRIPT
LANGUAGE="JavaScript">
<!-- Hide from other browsers
document.write('<IMG
SRC="welcome.gif">');
document.write("<H1>Greetings,
");
document.write(prompt("Enter your
name:", "Name"));
document.write(". Welcome to
Netscape! </H1>");
// Stop hiding from other
browsers -->
</SCRIPT>
The prompt method doesn't need to be prefixed by document because it is
part of the window object. If the object name is missing, then window
object is assumed.
alert dialog box
Is useful to show some information in a dialog box
alert("Click
OK to continue.");
useful to point out incorrect information in a form or invalid result
from a calculation, other messages
<SCRIPT
LANGUAGE="JavaScript">
<!-- Hide from other browsers
document.write('<IMG SRC="welcome.gif">');
alert("Welcome to my page !");
document.write("<H1>Greetings, ");
document.write(prompt("Enter your name:", "Name"));
document.write(". Welcome to Netscape! </H1>");
// Stop hiding from other browsers -->
</SCRIPT>
JavaScript Data Types
JavaScript provides four basic data types
- Numbers as in 21 and 32.62 - integers and floating point numbers
- Strings as in "Hello" and "There" - strings must be enclosed with
a pair of single or double quotation marks
- Boolean either true or false
- Null special keyword for a nothing value - when you create a
variable and haven't assigned a value to it yet
JavaScript Casting
JavaScript is a loosely typed programming language
- the type of a literal or a variable is not defined when a
variable is created and can, at times, change based on context
- you can get away with mixing data of different types
- When combining literals of different types, the first type is used
- for example 'Count to' + 10 becomes 'Count to 10'
- cannot do 2.5 + '10' and get 12.5
use parseInt() and parseFloat() functions to convert strings to
integers or floats.
- parseInt( '12' ) returns
the integer 12
- parseFloat( '33.23' )
returns 33.23
JavaScript - Variables
Variables in JavaScript can be of any data type
<SCRIPT
LANGUAGE="JavaScript">
<!-- Hide from other browsers
var name=prompt("Enter your name:", "Name");
document.write('<IMG SRC="welcome.gif">');
document.write("<H1> Greetings, " + name + ". Welcome to
my page! </H1>");
// Stop hiding from other browsers -->
</SCRIPT>
The following assignment statements are equivalent:
var example;
example = "Here is an example";
var example = "Here is an example";
Variable names are case sensitive and must start with a letter or an
underscore
JavaScript Expressions
Assignment which assigns a value to a
variable
Arithmetic evaluates to a number
- x += y; // x is now 15 (10 + 5)
- x *= y; // x is now 75 (15 * 5)
- x /= y; // x is now 15 (75 / 5)
- x %= y; // x is now 0 (15 / 5 leaves 0 remainder )
Reset x and y to 10 and 5
- x++; // increment operator; x
is now 11
- y--; // decrement operator; y
is now 4
- z = ++y; // z is 5 and y is now 5
- z = --x; // z is 10 and x is now 10
String evaluates to a string
A = "Today" + " is Friday"; // A is "Today is Friday"
Logical evaluates to a boolean value
- logical AND operator is && (the double
ampersand, no spaces)
- logical OR operator is || (the double
pipe or vertical bar, no spaces)
- logical not operator is ! (the
exclamation mark)
comparison operators
- < less than
- <= less than or equal to
- > greater than
- >= greater than or equal to
- == equal to (note - no spaces)
- != not equal to
x
= 10;
y = 5;
( x < y ) && ( x == 5
) // is false
( x > y ) || ( x < 5 )
// is true
JavaScript Conditional
as in C, C++
(condition) ? value1 : value2;
if (condition) evaluates to true, then value1 is returned; otherwise,
value2 is returned
JavaScript String
concatenation operator is +
"Welcome to " + "my site!" becomes "Welcome to my site!"
welcome += " Thank-you." adds the string "Thank-you." to the end of the
string variable called welcome.
JavaScript - if construct
Syntax:
if
(condition is true) {
Javascript commands if true
} else {
Javascript commands if
false
}
if ( day ==
"Saturday") {
document.writeln("It's the weekend!");
} else {
document.writeln("It's not Saturday.");
}
JavaScript - Confirm
The confirm method allows the user to select an OK button or a Cancel
button. Confirm returns true if OK is clicked, false if Cancel is
clicked.
if
(confirm("Press OK to retry.")) {
response = prompt("What
is 2+2", "3");
}
An example using confirm:
<HTML><HEAD><TITLE>An
Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide from older browsers
// define some variables
var question = "What is 10+10?";
var answer = 20;
var correct = '<IMG SRC="correct.gif">';
var incorrect ='<IMG SRC="incorrect.gif">';
// ask the question
var response = prompt(question,"0");
// check the answer
if (response != answer) {
// wrong answer; retry once
if (confirm("Wrong! Press OK for a second chance."))
response = prompt(question,"0");
}
// check the answer
var output = (response == answer) ? correct : incorrect;
// stop hiding from older browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide from older browsers
document.write(output);
// stop hiding from older browsers -->
</SCRIPT>
</BODY></HTML>
JavaScript - Functions - creating.
Defined using the function statement
function
function_name( parameters, arguments) {
command block
}
For example:
function
printName( name ) {
document.write("<HR>Your
Name is <B><I>");
document.write(
name );
document.write("</B></I><HR>");
}
functions should be defined in the header. This ensures that all
functions have been parsed before it is possible for user events to
invoke a function
eval() method
evaluates a string to a numeric
e.g. eval("4 + 5") returns a
value of 9
Examples
<SCRIPT
LANGUAGE="JavaScript">
<!-- hide from
older browsers
// define function
testQuestion()
function
testQuestion(question) {
// define
some local variables
var answer
= eval(question);
var output
= "What is " + question + "?";
var correct
= '<IMG SRC="correct.gif">';
var
incorrect = '<IMG SRC="incorrect.gif">';
// ask the
question
var
response=prompt(output,"0");
// check
the result
return
(response == answer) ? correct : incorrect;
}
// stop hiding from older
browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT
LANGUAGE="JavaScript">
<!-- hide from
older browsers
var result =
testQuestion("4 + 5");
document.write(result);
// stop hiding from
older browsers -->
</SCRIPT>
JavaScript - Dates
variable = new Date( parameters )
if no parameters are supplied, then the current date is used.
- var today = new Date(); // the date right now
- var birthday = new Date( 1962, 8, 24);
- var party = new Date( 96, 3, 23, 8, 0, 0);
- var the_date = new Date("October, 15, 1998");
a Date object, like other objects, has methods associated with it
- getDate()returns the day of the month
- getDay() returns the day of the week (0=Sunday, 1=Monday,)
- getHours() returns the hours
- getMinutes() returns the minutes
- getMonth() returns the month (0=January, 1=February,)
- getSeconds() returns the seconds
- getTime() returns the complete time elapsed in milliseconds since
January 1, 1970
- getYear() returns the number of years
Methods must be applied to objects using the format of object_name.method_name() as in
- var today = new Date();
- var Day = Today.getDate();
example:
<HEAD><TITLE>Day
Test using Javascript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--Hide from non-JavaScript browsers
// This function calculates the number of days until Christmas
function XmasDays(Month, Day, Year) {
var DayCount = (25-Day) + 30;
return DayCount;
}
// Stop hiding -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--Hide from non-JavaScript browsers
// Get date information
var Today = new Date("November 1, 1998");
var ThisDay = Today.getDate();
var ThisMonth = Today.getMonth() + 1;
var ThisYear = Today.getYear();
document.write("Today is "+ThisMonth+"/"+ThisDay+"/"+
ThisYear+"<BR>");
// Get number of days until Christmas
var DaysLeft = XmasDays(ThisMonth, ThisDay, ThisYear);
document.write("Only " + DaysLeft + " days until Christmas");
// Stop hiding -->
</SCRIPT>
Arrays in JavaScript
An array is an ordered collection of values referenced by a single
variable name.
- Weekday[1]="Monday";
- Weekday[2]="Tuesday";
- Weekday[3]="Wednesday";
- Weekday[4]="Thursday";
- Weekday[5]="Friday";
- Weekday[6]="Saturday";
- Weekday[7]="Sunday";
Each element is identified by an index, the number appearing in the
brackets. For example, the element "Monday" has an index of 1. In the
Weekday array there are actually eight elements in total. The first
element is Weekday[0], and it has the null value.
The syntax for creating an array variable is
var
variable = new Array( size );
specifying the size is optional. Javascript will automatically increase
the size of the array as you add more elements.
var Month = new
Array();
Month[12]
= "December";
Javascript will create 13 elements for the Month array all having null
values except for the Month[12] element.
Looping
A loop is a set of instructions that is run repeatedly. There are two
kinds of loops: a loop that repeats a set number of times, and a loop
that will continually repeat until a condition is met.
The For loop is the first kind
Syntax:
for (start;
stop; update) {
Javascript commands
}
// this will repeat
exactly three times
for (Num=1; Num<4; Num++) {
document.write("The value
of Num is " + Num + "<BR>");
}
- for (i=10; i>0; i--) // this loop will repeat 10 times
- for (j=0; j<=36; j+=5) // this loop will repeat 8 times
The While loop is the second kind
Syntax:
while
( condition is true ) {
Javascript commands
}
// repeats
three times
var Num = 1;
while (Num < 4) {
document.write("The value of Num is " + Num);
Num++;
}
JavaScript Resources