You are on page 1of 34

WKU/CCI/IS Fundamentals of Internet Programming I

Chapter 4
JavaScript
4.1 Overview of JavaScript
What is JavaScript?

JavaScript is a dynamic computer programming language. It is lightweight and most commonly


used as a part of web pages, whose implementations allow client-side script to interact with the
user and make dynamic pages. It is an interpreted programming language with object-oriented
capabilities. JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the
language has been embedded in Netscape, Internet Explorer, and other web browsers. The
ECMA-262 Specification defined a standard version of the core JavaScript language.

 JavaScript is a lightweight, interpreted programming language.


 Designed for creating network-centric applications.
 Complementary to and integrated with Java.
 Complementary to and integrated with HTML.
 Open and cross-platform.

Client-Side JavaScript

Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser. It means
that a web page need not be a static HTML, but can include programs that interact with the user,
control the browser, and dynamically create HTML content. The JavaScript client-side
mechanism provides many advantages over traditional CGI server-side scripts. For example, you
might use JavaScript to check if the user has entered a valid e-mail address in a form field. The
JavaScript code is executed when the user submits the form, and only if all the entries are valid,
they would be submitted to the Web Server. JavaScript can be used to trap user-initiated events
such as button clicks, link navigation, and other actions that the user initiates explicitly or
implicitly.

Advantages of JavaScript

The merits of using JavaScript are:

 Less server interaction: You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors: They don't have to wait for a page reload to see if they
have forgotten to enter something.
 Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
 Richer interfaces: You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

Compiled By Fasil 1
WKU/CCI/IS Fundamentals of Internet Programming I

Limitations of JavaScript

We cannot treat JavaScript as a full-fledged programming language. It lacks the following


important features:

 Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reasons.
 JavaScript cannot be used for networking applications because there is no such support
available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities. Once again,
JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTML pages.

JavaScript Development Tools

One of major strengths of JavaScript is that it does not require expensive development tools. You
can start with a simple text editor such as Notepad. Since it is an interpreted language inside the
context of a web browser, you don't even need to buy a compiler.

To make our life simpler, various vendors have come up with very nice JavaScript editing tools.
Some of them are listed here:

 Microsoft FrontPage: Microsoft has developed a popular HTML editor called FrontPage.
FrontPage also provides web developers with a number of JavaScript tools to assist in the
creation of interactive websites.
 Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very popular HTML
and JavaScript editor in the professional web development crowd. It provides several
handy prebuilt JavaScript components, integrates well with databases, and conforms to
new standards such as XHTML and XML.
 Macromedia HomeSite 5: HomeSite 5 is a well-liked HTML and JavaScript editor from
Macromedia that can be used to manage personal websites effectively.
 Others: SublimeText3, Notepad++, aptana ….

Where is JavaScript Today?

The ECMAScript Edition 5 standard will be the first update to be released in over four years.
JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the difference between the
two is extremely minor. The specification for JavaScript 2.0 can be found on the following site:
http://www.ecmascript.org/ Today, Netscape's JavaScript and Microsoft's JScript conform to
the ECMAScript standard, although both the languages still support the features that are not a
part of the standard.

What Can JavaScript Do?

 JavaScript can change HTML Content


 JavaScript can change HTML attribute
 JavaScript can change HTML Styles
 JavaScript can validate data

Compiled By Fasil 2
WKU/CCI/IS Fundamentals of Internet Programming I

4.2 The HTML <Script> tag


JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page. The <script> tag alerts the browser program to start
interpreting all the text between these tags as a script. A simple syntax of your JavaScript will
appear as follows.

<script>
Block code
</script>
JavaScript where to?

You can place any number of scripts in an HTML document. Scripts can be placed in the <body>,
or in the <head> section of an HTML page, or in both. Scripts can also be placed in external files.
External scripts are practical when the same code is used in many different web pages. JavaScript
files have the file extension .js. To use an external script, put the name of the script file in the src
(source) attribute of the <script> tag:

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
You can place an external script reference in <head> or <body> as you like. The script will behave
as if it was located exactly where the <script> tag is located.

Advantages of External JavaScript

 It separates HTML and code.

 It makes HTML and JavaScript easier to read and maintain

 Cached JavaScript files can speed up page loads.

4.3 JavaScript Syntax


JavaScript syntax is the rules, how JavaScript programs are constructed. The JavaScript syntax is
similar to C# and Java.

JavaScript Programs

A computer program is a list of "instructions" to be "executed" by the computer. In a


programming language, these program instructions are called statements. JavaScript is
a programming language. JavaScript statements are separated by semicolon.

Compiled By Fasil 3
WKU/CCI/IS Fundamentals of Internet Programming I

4.4 JavaScript Statements


In HTML, JavaScript statements are "instructions" to be "executed" by the web browser. JavaScript
statements are composed of: Values, Operators, Expressions, Keywords, and Comments. Most
JavaScript programs contain many JavaScript statements. The statements are executed, one by
one, in the same order as they are written. JavaScript ignores multiple spaces. You can add white
space to your script to make it more readable.

 JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be
performed. JavaScript keywords are reserved words. Reserved words cannot be used as names
for variables.

Some Examples of keywords: var, function, if, for, break, switch ……..

 JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Two types of comments
Single line comment: Any text between // and the end of a line, will be ignored by JavaScript
Multiline Comment: Any text between /* and */ will be ignored by JavaScript.

4.5 JavaScript Variables


JavaScript variables are containers for storing data values.

Declaring Variables

You declare a JavaScript variable with the var keyword:

var x;
var y;
A variable declared without a value will have the value undefined.

You can also assign a value to the variable when you declare it:

var x = 5;
var y = 6;
var z = x + y;
From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 z stores the value 11

Compiled By Fasil 4
WKU/CCI/IS Fundamentals of Internet Programming I

 JavaScript Identifier

Identifiers are names for a variable

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

 JavaScript Datatypes
o JavaScript Strings - A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
var s1=‘john’;
o JavaScript Numbers - JavaScript has only one type of numbers. Numbers can be written
with, or without decimals:
var x=23;
var x=23.00;
Extra-large or extra small numbers can be written with scientific (exponential) notation:
var y=15e5;
o JavaScript Array - JavaScript arrays are written with square brackets. Array items are
separated by commas:
var array1=[“IS”, “CS” , “SE”];
o JavaScript Object - JavaScript objects are written with curly braces. Object properties are
written as name:value pairs, separated by commas.
var person = {firstName:"John", lastName:"Doe", age:50};
o JavaScript Boolean - Booleans can only have two values: true or false.
var x = true;
var y = false;

Compiled By Fasil 5
WKU/CCI/IS Fundamentals of Internet Programming I

4.6 JavaScript Operators


Arithmetic operators

Symbol Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
++ Increment
-- Decrement

Assignment Operators

Operator Example Same as


= x=y x=y
+= 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

Comparison Operators

Operator Description
== Equal to
!= Not Equal to
=== Equal Value and Equal type
!== Not Equal value and type
< Less than
> Greater than
<= Less than or Equal
>= Greater than or Equal

Logical Operators

Assume variable A holds 1 and variable B holds 0, then:

Operator Description Example

Called Logical AND operator. If both


&& the operands are non-zero, then (A && B) is false.
condition becomes true.

Compiled By Fasil 6
WKU/CCI/IS Fundamentals of Internet Programming I

Called Logical OR Operator. If any of


|| the two operands is non-zero, then (A || B) is true.
condition becomes true.

Called Logical NOT Operator. Use to


reverses the logical state of its
! !(A && B) is true.
operand. If a condition is true, then
Logical NOT operator will make false.

Reading Assignment: Bitwise operator

4.7 JavaScript Conditional Statements


The if statement
1. Simple if statement

The if keyword is used to execute a statement or block only if a condition is fulfilled. Its
form is: if (condition)
statement
Where condition is the expression that is being evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the program
continues right after this conditional structure.
Syntax
if (expression)
statements;
For example, the following code fragment prints x is 100 only if the value stored in the x
variable is indeed 100:

if (x == 100)
document.write( "x is 100");

If we want more than a single statement to be executed in case that the condition is true
we can specify a block using braces { }:

if (x == 100)
{
document.write("x is ");
document.write( x);
}

Compiled By Fasil 7
WKU/CCI/IS Fundamentals of Internet Programming I

<html>
<body>
<script type="text/javascript">
<!--
var age = prompy(“Enter your age”,18);
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
</body>
</html>

2. The if else statement

We can additionally specify what we want to happen if the condition is not fulfilled by using the
keyword else. Its form used in conjunction with if is:
if (condition)
statement1;
else
statement2;

For example:

if (x == 100)
document.write( "x is 100");
else
document.write("x is not 100");

prints on the document x is 100 if indeed x has a value of 100, but if it has not -and only if not- it
prints out x is not 100.
3. The if else if statement

The if + else structures can be concatenated with the intention of verifying a range of values. The
following example shows its use telling if the value currently stored in x is positive, negative or
none of them (i.e. zero):

Syntax
if (x > 0)
alert("x is positive");
else if (x < 0)
alert("x is negative");
else
alert("x is 0");

Compiled By Fasil 8
WKU/CCI/IS Fundamentals of Internet Programming I

Remember that in case that we want more than a single statement to be executed, we must group
them in a block by enclosing them in braces { }.
<!DOCTYPE html>
<html>
<body>

<p>Click the button to get a time-based greeting:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var greeting;
var time = new Date().getHours();
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
}
</script>

</body>
</html>

4. The Nested if Statement

 One or more if statements can be nested with in another if statement.


 The nesting will be used to test multiple conditions to perform a task.
 It is always recommended to indent nested if statements to enhance readability of a
program

Compiled By Fasil 9
WKU/CCI/IS Fundamentals of Internet Programming I

 The General Syntax might be:


if (expression1)
{
if (expression2)
statementsN;
else
statementsM;
}
else
{
if (expression3)
statementsR;
else
statementsT;
}

 StatementsN will be executed if and only if “expression1” and “expression2” are


evaluated and if the outcome of both is none zero (TRUE).
 StatementsM will be executed if and only if “expression1” is TRUE and “expression2”
is FALSE.
 StatementsR will be executed if and only if “expression1” is FALSE and “expression3”
is TRUE.
 StatementsT will be executed if and only if “expression1” is FLASE and “expression3”
is FALSE.

 Let's have an example on nested if statements

var testScore, age;


testScore=prompt(“ Enter your test score ”,10);
testScore=parseInt(testScore);
age=prompt(“ enter your age:”,10);
age=parseInt(age);
if(testScore >= 70)
{
if(age < 10)
alert(“ You did a great job”);
else
alert(“ You did pass”);
}
else
alert(“ You did not pass”);

Compiled By Fasil 10
WKU/CCI/IS Fundamentals of Internet Programming I

Switch Statement

The if and if/else statements become quite confusing when nested too deeply, and
JavaScript offers an alternative.

The general form of the switch statement is:

switch (expression)
{
case valueOne: statement;
break;
case valueTwo: statement;
break;
....
case valueN: statement;
break;
default: statement;
}
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}

Use weekday number to calculate weekday name: (Sunday=0, Monday=1,


Tuesday=2 ...)

Compiled By Fasil 11
WKU/CCI/IS Fundamentals of Internet Programming I

4.8 JavaScript Loops


Loops are used to execute a set of code several times.

1. The while Loop

 The while statement (also called while loop) provides a way of repeating a statement or a
block as long as a condition holds / is true.
 The general form of the while loop is:
while(expression)
statements;

 First expression (called the loop condition) is evaluated. If the outcome is non zero then
statement (called the loop body) is executed and the whole process is repeated. Otherwise, the
loop is terminated.
Example
Try the following example to implement while loop.
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Example 2:
The following script will request the user to insert age until the user inserts valid age(1-130).
<!doctype html>
<html>
<head>
<title>While loop Test</title>
</head>
<body>
<script>
var x=0;
while((x<1) || (x>130)){
x=prompt("enter your age");

Compiled By Fasil 12
WKU/CCI/IS Fundamentals of Internet Programming I

}
alert("Thanks");
</script>
</body>
</html>

2. The do while Loop

 The do statement (also called the do while loop) is similar to the while statement,
except that its body is executed first and then the loop condition is examined.
 In do…while loop, we are sure that the body of the loop will be executed at least once.
Then the condition will be tested.
 The general form is:
do
{
statement;
}
while(expression);

Change the above while loop statements to do-while.

3. The for Loop

 The “for” statement is used to repeatedly execute a block of instructions until a


specific condition fails.
 The General Syntax is:

for(expression1 ; expression2 ; expression3)


statements;

 The for loop has three expressions:


 expression1: is one or more statements that will be executed only once and before the
looping starts.
 Expression2: is the part that decides whether to proceed with executing the
instructions in the loop or to stop. Expression2 will be evaluated each time before the
loop continues. The output of expression2 should be either non zero (to proceed with
the loop) or zero (to stop the loop) to represent true and false output respectively.
 Expression3: is one or more statements that will be executed after each iteration.

Compiled By Fasil 13
WKU/CCI/IS Fundamentals of Internet Programming I

 Thus, first expression1 is evaluated and then each time the loop is executed,
expression2 is evaluated. If the outcome of expression2 is non zero then statements is
executed and expression3 is evaluated. Otherwise, the loop is terminated.

The general format can be expressed as follows:

for(initialization ; condition ; increase/decrease)


statement;
Steps of execution of the for loop:
1. Initialization is executed. (will be executed only once)
2. Condition is checked, if it is true the loop continues, otherwise the loop finishes and
statement is skipped.
3. Statement is executed.
4. Finally, whatever is specified in the increase or decrease field is executed and the loop
gets back to step two.

4.9 JavaScript Functions


A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small
and manageable functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. You must have seen functions like alert() and
write() in the earlier chapters. We were using these functions again and again, but they had been
written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to write your
own functions in JavaScript. JavaScript functions are defined with the function keyword.
You can use a function declaration or a function expression.
o Function Declaration
Declared functions are not executed immediately. They are "saved for later use", and
will be executed later, when they are invoked (called upon).
function functionName(parameters) {
code to be executed
}
o Function Expression
A function expression can be stored in a variable. After a function expression has
been stored in a variable, the variable can be used as a function:
var x = function (a, b) {return a * b};
var z = x(4, 3);

Compiled By Fasil 14
WKU/CCI/IS Fundamentals of Internet Programming I

o The function constructor


The function statement is not the only way to define a new function; you can define your
function dynamically using Function() constructor along with the new operator.

Syntax

<script type="text/javascript">

var variablename = new Function(Arg1, Arg2..., "Function Body");

</script>

Example

<html>
<head>
<script type="text/javascript">
var func = new Function("x", "y", "return x*y;");
function secondFunction(){
var result;
result = func(10,20);
document.write ( result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

o Self-invoking function

Function expressions can be made "self-invoking". A self-invoking expression is invoked (started)


automatically, without being called. Function expressions will execute automatically if the
expression is followed by (). You cannot self-invoke a function declaration. You have to add
parentheses around the function to indicate that it is a function expression:

(function () {
var x = "Hello!!"; // I will invoke myself
})();

Compiled By Fasil 15
WKU/CCI/IS Fundamentals of Internet Programming I

o Function Hoisting

Earlier in this tutorial, you learned about "hoisting". Hoisting is JavaScript's default behavior
of moving declarations to the top of the current scope. Hoisting applies to variable
declarations and to function declarations. Because of this, JavaScript functions can be called
before they are declared:

myFunction(5);

function myFunction(y) {
return y * y;
}

Functions defined using an expression are not hoisted.

o JavaScript Function Parameters

We can pass different parameters while calling a function. These passed parameters can be
captured inside the function and any manipulation can be done over those parameters. A function
can take multiple parameters separated by comma.

Example: Let’s try simple example


<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>

</html>

Compiled By Fasil 16
WKU/CCI/IS Fundamentals of Internet Programming I

o Function Closure
The ability to treat functions as values, combined with the fact that local variables are “re-created”
every time a function is called, brings up an interesting question. What happens to local variables
when the function call that created them is no longer active? The following code shows an
example of this. It defines a function, wrapValue, which creates a local variable. It then returns a
function that accesses and returns this local variable.
functionwrapValue(n){
var l o c a l V a r i a b l e = n ;
r e t u r n f u n c t i o n () { r e t u r n l o c a l V a r i a b l e ; };
}
var wrap1 = w r a p V a l u e (1) ;
var wrap2 = w r a p V a l u e (2) ;
c o n s o l e . log ( wrap1 () ) ;
// ! 1
c o n s o l e . log ( wrap2 () ) ;
// ! 2
This is allowed and works as you’d hope—the variable can still be accessed. In fact, multiple
instances of the variable can be alive at the same time, which is another good illustration of the
concept that local variables really are re-created for every call—different calls can’t trample on
one another’s local variables. This feature—being able to reference a specific instance of local
variables in an enclosing function—is called closure. A function that “closes over” some local
variables is called a closure. This behavior not only frees you from having to worry about lifetimes
of variables but also allows for some creative use of function values. With a slight change, we can
turn the previous example into a way to create functions that multiply by an arbitrary amount.
function multiplier( factor) {
return function ( number ) {
return number * factor ;
};
}
var twice = multiplier(2) ;
console . log ( twice (5) ) ;
// ! 10
The explicit localVariable from the wrapValue example isn’t needed since a parameter is itself a
local variable. Thinking about programs like this takes some practice. A good mental model is to
think of the function keyword as “freezing” the code in its body and wrapping it into a package
(the function value). So when you read return function(...){...}, think of it as returning a handle to
a piece of computation, frozen for later use. In the example, multiplier returns a frozen chunk of
code that gets stored in the twice variable. The last line then calls the value in this variable, causing
the frozen code (return number * factor;) to be activated. It still has access to the factor variable
from the multiplier call that created it, and in addition it gets access to the argument passed when
unfreezing it, 5, through its number parameter.

A variable created without a var keyword will be treated as global variable even
though it is created inside a function.

Compiled By Fasil 17
WKU/CCI/IS Fundamentals of Internet Programming I

4.10 JavaScript Events


JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page. When the page loads, it is called an event. When the user clicks a
button, that click too is an event. Other examples include events like pressing any key, closing a
window, resizing a window, etc. Developers can use these events to execute JavaScript coded
responses, which cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable. Events are a part of the
Document Object Model (DOM) Level 3 and every HTML element contains a set of events
which can trigger JavaScript Code.
 Common HTML Events
o Onclick Event Type: This is the most frequently used event type which occurs when a user
clicks the left button of his mouse. You can put your validation, warning etc., against this
event type.
Example:
<html>
<head>
<script type="text/javascript">

function sayHello() {
document.write ("Hello World")
}
</script>

</head>
<body>
<p> Click the following button and see result</p>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

o onsubmit event type: onsubmit is an event that occurs when you try to submit a form.
You can put your form validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form
will be submitted, otherwise it will not submit the data.
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>

Compiled By Fasil 18
WKU/CCI/IS Fundamentals of Internet Programming I

</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>

o onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and the
onmouseout triggers when you move your mouse out from that element.
Try the following example.
<html>
<head>
<script type="text/javascript">
<!--
function over() {
//document.write ("Mouse Over");
document.getElementById("d1").innerHTML="mouse over";
}
function out() {
//document.write ("Mouse Out");
document.getElementById("d1").innerHTML="mouse out";
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div id="d1" onmouseout="out()" onmouseover="over()" >
<h2> This is inside the division </h2>
</div>
<p>this is outside the div</p>
</body>
</html>

4.11 JavaScript DOM


Every web page resides inside a browser window which can be considered as an object. A
Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.
The way a document content is accessed and modified is called the Document Object Model, or
DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document.
 Window object: Top of the hierarchy. It is the outmost element of the object hierarchy.

Compiled By Fasil 19
WKU/CCI/IS Fundamentals of Internet Programming I

 Document object: Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.

 Form object: Everything enclosed in the <form>...</form> tags sets the form object.

 Form control elements: The form object contains all the elements defined for that object
such as text fields, buttons, radio buttons, and checkboxes.

Here is a simple hierarchy of a few important objects:

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

o HTML DOM Programming Interface

In the DOM, all HTML elements are defined as objects. The programming interface is the
properties and methods of each object. HTML DOM methods are actions you can perform on
HTML Elements (like add or deleting an HTML element). HTML DOM properties are values of
HTML Elements that you can set or change (like changing the content of an HTML element).
The HTML DOM can be accessed with JavaScript (and with other programming languages).
The HTML DOM Document
The document object is your webpage. The document object is the owner of all other objects
in your web page. If you want to access objects in an HTML page, you always start with

Compiled By Fasil 20
WKU/CCI/IS Fundamentals of Internet Programming I

accessing the document object. Below are some examples of how you can use the document
object to access and manipulate HTML.

 Finding HTML elements


Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find
the elements first. There are a couple of ways to do this:

Method Description

document.getElementById() Find an element by its id

document.getElementsByClassName() Find elements by class name

document.getElementsByTagName() Find elements by tag name

Example: Finding Element By Id


var x = document.getElementById("x"); //Returns an element with id=”x”
Example: Finding elements by tag name
var y = document.getElementsByTagName("p");//returns an array of <p> elements
Example: Finding elements by class name
document.getElementsByClassName("c1");// returns a list of all HTML elements with
//class="c1".
 Finding HTML Objects
Some Examples are

Property Description

document.anchor Returns all <a> elements that have a name attribute


Returns the <body> element
document.body

document.cookie Returns the document's cookie

document.forms Returns all <form> elements

document.head Returns the <head> element

document.images Returns all <img> elements

Compiled By Fasil 21
WKU/CCI/IS Fundamentals of Internet Programming I

document.title Returns the <title> element

document.URL Returns the complete URL of the document

 Changing Html Elements


The HTML DOM allows JavaScript to change the content of HTML elements.

Methods Description

element.innerHTML= Change the inner HTML of an element

element.attribute= Change the attribute of an HTML element

element.setAttribute(attribute,value) Change the attribute of an HTML element

element.style.property= Change the style of an HTML element

The above table is explained easily below:


o Changing the content of an HTML

 The easiest way to modify the content of an HTML element is by using


the innerHTML property.
 To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML = new HTML

This example changes the content of a <p> element:

<html>
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

</body>
</html>

o Changing the value of an attribute


 To change the value of an HTML attribute, use this syntax:

Compiled By Fasil 22
WKU/CCI/IS Fundamentals of Internet Programming I

document.getElementById(id).attribute=new value
 This example changes the value of the src attribute of an <img> element:
<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>

Example explained:

 The HTML document above contains an <img> element with id="myImage"


 We use the HTML DOM to get the element with id="myImage"
 A JavaScript changes the src attribute of that element from "smiley.gif" to
"landscape.jpg".

o Changing HTML style


 To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
 The following example changes the style of a <p> element:

Example

<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

Compiled By Fasil 23
WKU/CCI/IS Fundamentals of Internet Programming I

</body>
</html>

 Adding and Deleting Elements

Method Description

document.createElement() Create an HTML

elementdocument.removeChild() Remove an HTML

elementdocument.appendChild() Add an HTML

elementdocument.replaceChild() Replace an HTML

elementdocument.write(text) Write into the HTML output stream

 Adding HTML Events


The HTML DOM allows you to execute code when an event occurs.

Events are generated by the browser when "things happen" to HTML elements:

 An element is clicked on
 The page has loaded
 Input fields are changed

Method Descriptoin

document.getElementById(id).onclick= Adding event handler code to an


function(){code} onclick event

This example changes the style of the HTML element with id="id1", when the user
clicks a button:

Compiled By Fasil 24
WKU/CCI/IS Fundamentals of Internet Programming I

Example

<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My Heading 1</h1>

<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

</body>
</html>

o HTML DOM Events


HTML DOM allows JavaScript to react to HTML events.
o Reacting To events
A JavaScript can be executed when an event occurs.

Examples of HTML events:

 When a user clicks the mouse


 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key

o Event Attributes

 The onload and onunload events


The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version,
and load the proper version of the web page based on the information. The onload and
onunload events can be used to deal with cookies.

Example:
<body onload="checkCookies()">

Compiled By Fasil 25
WKU/CCI/IS Fundamentals of Internet Programming I

 The onchange event


The onchange event are often used in combination with validation of input fields.

Below is an example of how to use the onchange. The upperCase() function will be
called when a user changes the content of an input field.

<!DOCTYPE html>
<html>

<head>

<script>

function myFunction() {

var x = document.getElementById("fname");

x.value = x.value.toUpperCase();

</script>

</head>

<body>

Enter your name: <input type="text" id="fname"


onchange="myFunction()">

<p>When you leave the input field, a function is triggered which


transforms the input text to upper case.</p>

</body>

</html>

 The onmouseover and onmouseout event


The onmouseover and onmouseout events can be used to trigger a function
when the user mouses over, or out of, an HTML element.
Example:
<!DOCTYPE html>

<html>

Compiled By Fasil 26
WKU/CCI/IS Fundamentals of Internet Programming I

<body>

<div onmouseover="mOver(this)" onmouseout="mOut(this)"

style="background-
color:#D94A38;width:120px;height:20px;padding:40px;">

Mouse Over Me</div>

<script>

function mOver(obj) {

obj.innerHTML = "Thank You"

function mOut(obj) {

obj.innerHTML = "Mouse Over Me"

</script>

</body>

</html>

 The onmousedown, onmouseup and onclick events


The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First
when a mouse-button is clicked, the onmousedown event is triggered, then, when the
mouse-button is released, the onmouseup event is triggered, finally, when the mouse-
click is completed, the onclick event is triggered.
Example:
<!DOCTYPE html>

<html>

<body>

<div onmousedown="mDown(this)" onmouseup="mUp(this)"

Compiled By Fasil 27
WKU/CCI/IS Fundamentals of Internet Programming I

style="background-color:#D94A38;width:90px;height:20px;padding:40px;">

Click Me</div>

<script>

function mDown(obj) {

obj.style.backgroundColor = "#1ec5e5";

obj.innerHTML = "Release Me";

function mUp(obj) {

obj.style.backgroundColor="#D94A38";

obj.innerHTML="Thank You";

</script>

</body>

</html>

4.12 JavaScript Form Validation


Data validation is the process of ensuring that computer input is clean, correct, and useful.

Typical validation tasks are:

 Has the user filled in all required fields?


 Has the user entered a valid date?
 Has the user entered text in a numeric field?

Most often, the purpose of data validation is to ensure correct input to a computer
application.

Compiled By Fasil 28
WKU/CCI/IS Fundamentals of Internet Programming I

Validation can be defined by many different methods, and deployed in many different
ways.

Server side validation is performed by a web server, after input has been sent to the server.

Client side validation is performed by a web browser, before input is sent to a web server.
HTML Constraint validation

HTML5 introduced a new HTML validation concept called constraint validation.

HTML constraint validation is based on:

 Constraint validation HTML Input Attributes


 Constraint validation CSS Pseudo Selectors
 Constraint validation DOM Properties and Methods

o Constraint validation HTML input attributes

Attribute Description
disabled specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern specifies the value pattern of an input element
required Specifies that the input field requires an element
type Define the minimum value of an input element

o Constraint validation CSS pseudo selectors


Selector Description
:disabled Selects input elements with the "disabled" attribute specified
:invalid Selects input elements with invalid values
:optional Selects input elements with no "required" attribute specified
:required Selects input elements with the "required" attribute specified
:valid Selects input elements with valid values

o Constraint Validation DOM methods


Property Description
checkValidity() Returns true if an input element contains valid data.
setCustomValidity() Sets the validationMessage property of an input element.

o Constraint Validation DOM properties


property Description
validity Contains boolean properties related to the validity of an
input element.

Compiled By Fasil 29
WKU/CCI/IS Fundamentals of Internet Programming I

validationmessage Contains the message a browser will display when the


validity is false.
willvalidate Indicates if an input element will be validated.

o Validity Properties
The validity property of an input element contains a number of properties related to the
validity of data:
Property Description
customError Set to true, if a custom validity message is set.
patternMismatch Set to true, if an element's value does not match its pattern
attribute.
rangeOverflow Set to true, if an element's value is greater than its max
attribute.
rangeUnderflow Set to true, if an element's value is less than its min attribute.

stepMismatch Set to true, if an element's value is invalid per its step attribute.
tooLong Set to true, if an element's value exceeds its maxLength
attribute.
typeMismatch Set to true, if an element's value is invalid per its type attribute.
valueMissing Set to true, if an element (with a required attribute) has no
value.
valid Set to true, if an element's value is valid.

4.13 JavaScript Cookies


 What are cookies

Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol.
But for a commercial website, it is required to maintain session information among different
pages. For example, one user registration ends after completing many pages. But how to maintain
users' session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor experience
or site statistics.

 How Cookies work

Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now,
when the visitor arrives at another page on your site, the browser sends the same cookie to the
server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields:
o Expires: The date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.

o Domain: The domain name of your site.

Compiled By Fasil 30
WKU/CCI/IS Fundamentals of Internet Programming I

o Path: The path to the directory or web page that set the cookie. This may be blank if you
want to retrieve the cookie from any directory or page.

o Secure: If this field contains the word "secure", then the cookie may only be retrieved
with a secure server. If this field is blank, no such restriction exists.

o Name=Value: Cookies are set and retrieved in the form of key-value pairs.

JavaScript can also manipulate cookies using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

 Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1=value1;key2=value2;expires=date";

Here the expires attribute is optional. If you provide this attribute with a valid date or time, then
the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when you
read the cookie value.

Example
Try the following. It sets a customer name in an input cookie.

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert ("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>

Compiled By Fasil 31
WKU/CCI/IS Fundamentals of Internet Programming I

</form>
</body>
</html>
Now your machine has a cookie called name. You can set multiple cookies using multiple
key=value pairs separated by comma.
 Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the document.cookie
object is the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons, where
name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows:
Example
Try the following example to get all the cookies.

<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Note: Here length is a method of Array class which returns the length of an array. We will
discuss Arrays in a separate chapter. By that time, please try to digest it.

Note: There may be some other cookies already set on your machine. The above code will
display all the cookies set on your machine.

Compiled By Fasil 32
WKU/CCI/IS Fundamentals of Internet Programming I

 Setting cookies expiry Date

You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting the ‘expires’
attribute to a date and time.
Example
Try the following example. It illustrates how to extend the expiry date of a cookie by 1
Month.

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

 Deleting Cookies

Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie
return nothing. To do this, you just need to set the expiry date to a time in the past.
Example
Try the following example. It illustrates how to delete a cookie by setting its expiry date to
one month behind the current date.

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"

Compiled By Fasil 33
WKU/CCI/IS Fundamentals of Internet Programming I

document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

Compiled By Fasil 34

You might also like