Chapter Three
JavaScript
Introduction
• JavaScript is used in millions of Web pages to improve the design, validate
forms, detect browsers, create cookies, …
• It is the most popular scripting language on the internet, and works in all
major browsers
• Scripting languages are usually interpreted rather than compiled
• Programs written in interpreted languages must be translated into machine
code every time they are run, they are typically slower than compiled
programs.
• Being interpreted does have its advantages:
• platform independence: the interpreter is built into Web browsers.
• often loosely typed and more forgiving than compiled languages
Purposes of JavaScript
• JavaScript gives HTML designers a programming tool: a scripting
language with a very simple syntax!
• JavaScript can put dynamic text into an HTML page:
• document.write("<h1>" + name + "</h1>") can write a variable text into an
HTML page
• can react to events
• can read and write HTML elements with id attribute
• can be used to validate data
• can be used to detect the visitor's browser
• can be used to create cookies: store and retrieve information on the
visitor's computer
Including JS in HTML
• Enclose JavaScript code in <SCRIPT>...</SCRIPT> tag pair
<SCRIPT LANGUAGE=”text/JavaScript”>
//your script here
</SCRIPT>
Or
<SCRIPT type=”text/JavaScript”>
//your script here
</SCRIPT>
• JavaScript code is case sensitive
• White space between words and tabs are ignored
• Line breaks are ignored except within a statement like: echo(“Hello <br>”)
• JavaScript statements end with a semi colon (;) if more than one statements are on the same
line
Where to insert JS
• Script in <head>...</head> section.
• Scripts to be executed when they are called, or when an event is triggered, are
placed in functions and they do not interfere with page content.
• Script in <body>...</body> section.
• To write page content, it should be placed in the body section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in external file and then include in <head>...</head> section.
• for external js file, use the SRC attribute of the <SCRIPT> tag to call
JavaScript code from an external text file.
• <SCRIPT type = "JavaScript" SRC = " url of javascript file"> </SCRIPT>
Input-Output in Java/ Message Boxes
• documents.write() method writes a string to a web page
• alert() or window.alert(): produces a browser alert box
• When an alert box pops up, the user will have to click "OK" to proceed
• Prompt box: is used to allow a user to enter something according to the prompt
• var y=window.prompt("please enter your name")
• window.alert(y)
• Confirm box: is often used if we want the user to verify or accept something
var r = confirm("Press a button")
if (r == true)
{ x="You pressed OK!"; }
else { x="You pressed Cancel!"; }
document.write (x);
• window.print() will print the current web page when executed.
• <input type="button" value="Print" onclick="window.print>
Variables and Data in JS
• Data in JavaScript may be text information (such as number, string, Boolean)
displayed on the screen by a JavaScript statement
• Declaring Variables: variables declared with var keyword
• var variablename;
• Variable name rules similar to c++, php and java
• Assigning Values to Undeclared Variables
• age=5; similar with var age=5;
• Re-declaring JavaScript Variables
• If we re-declare a JavaScript variable, it will not lose its original value.
var age=5;
var age; //still the value of age is 5
• JavaScript Comments
• Single line comment //
• Multiple line comment /* …..*/
• Operators are similar with c, c++, …
• Conditional statements
• If statement
• switch statement
<script type="text/javascript">
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
} else{
document.write("<b>Unknown Book</b>");
}
</script>
• for Loop:
var counter = 100;
var sum = 0;
for (var i = 0; i <= counter; i++) {
sum = sum + i;
}
document.write(“the sum is ” + sum);
• do...while Statement
i=1;
do
{
i += 1;
document.write(i);
} while (i < 5);
for...in loop
• This loop is used to loop through an object's properties.
• Syntax:
for (variablename in object){
statement or block to execute
}
• In each iteration one property from object is assigned to variablename and
this loop continues till all the properties of the object are exhausted.
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write("Exiting from the loop!");
Break, continue and label statements
• used to come out of a loop without reaching at its bottom or to skip a part of the code
block and want to start next iteration of the look when needed by users or programmers.
• To handle all such situations, JavaScript provides break, label and continue statements.
• These statements are used to immediately come out of any loop or to start the next
iteration of any loop.
• See example code
Using Arrays
• Create arrays:
• var array_name = [item1, item2, ...];
• var myArray = new makeArray(n) where n is the number of entries
• var numbers = [45, 4, 9, 16, 25]; also possible
• example:
var planet = new Array(9);
Planet[0] = “Mercuri”
Planet[1] = “Venus”
• Delete array elements: delete planet[2],
• length.planet; //returns 9 it does not change the array size
• Planet[2] //result: undefined
• array1.concat(array2):- used to concatenate arrays
• For example:
var array1 = new Array(1,2,3)
var array2 = new Array(“a”,”b”,”c”)
var array3 = array1.concat(array2)
// result: array with values 1,2,3,”a”,”b”,”c”
JS functions
• Function definition consists of the function keyword, followed by:
• The name of the function.
• A list of arguments to the function, enclosed in parentheses and separated by
commas.
function square(number) {
return number * number;
}
• See example: function.html
JS Objects
• JavaScript is an Object-Oriented Programming (OOP) language.
• A JavaScript object has properties and methods
• Example: String JavaScript object has length property and
toUpperCase() method
<script type="text/javascript">
var txt="Hello World!"
document.write(txt.length)//returns length
document.write(txt.toUpperCase())
</script>
Math Objects and Functions
• The predefined Math object has properties and methods for mathematical constants
and functions.
• For example, the Math object’s PI property has the value of pi (3.141...), which we would use in
an application as Math.PI.
• Similarly, standard mathematical functions are methods of Math. These include
trigonometric, logarithmic, exponential, and other functions
• For example, if we want to use the trigonometric function sine, we would write: Math.sin(1.56).
• Note that all trigonometric methods of Math take arguments in radians.
Date Object
• Most of date and time work is done with the Date object.
• The basic syntax for generating a new date object is as follows:
var dateObjectName = new Date([parameters])
• The parameter can be:
• new Date(“Month dd, yyyy hh:mm:ss”)
• new Date(“Month dd, yyyy”)
• new Date(yy,mm,dd,hh,mm,ss)
• new Date(yy,mm,dd)
Managing Events
• Events are user and browser activities to which we may respond dynamically
with a scripting language like JavaScript.
• The event that we used can be summarized as :-
• A mouse click
• Moussing over a hot spot on the web page
• Selecting an input box in an HTML form
• Submitting an HTML form
• A keystroke
• Example events:
• onabort - Loading of an image is interrupted
• onblur - An element loses focus
• ondblclick - Mouse double-clicks an object
• onclick - Mouse clicks an object
<head>
<script language="JavaScript">
function adder(num1, num2){
var sum = 0;
sum = num1 + num2;
document.write("The sum is " + sum);
}
function subtractor(num1, num2){
var difference = 0;
difference = num1 - num2;
document.write("The difference is " + difference);
}
</script>
</head>
<body>
<form name="event_example">
<input type="button" value="add" name="add" onClick="adder(10,30)">
<input type="button" value="subtract" name="subtract"
onClick="subtractor(20,50)">
</form>
</body>
Form Processing and Validation
• Forms are widely used on the Internet.
• The form input is often sent back to the server or mailed to a certain e-
mail account.
• With the help of JavaScript, the form input can easily be checked
before being sent.
• It is sent only if the input is valid
• Form data that typically are checked by a JavaScript could be:
• has the user left required fields empty?
• has the user entered a valid e-mail address?
• has the user entered a valid date?
• has the user entered text in a numeric field?
Validation example
<script>
function check (formName){
if (formName.urname.value == "")
alert("Please enter a string as your name!")
else
alert("Hi " + formName.urname.value + "! Name ok!");
if(formName.age.value < 0 || formName.age.value=="")
alert("Age should be number and greater than 0");
else
alert("Age ok");
}
</script>
<form name="first">
Enter your name: <input type="text" name="urname"> <br>
Enter your age: <input type="text" name="age"> <br>
<input type="button" name="validate" value="CheckInput “onClick ="check(this.form)">
Validation ….
• Basic Validation - First of all, the form must be checked to make sure data was entered into
each form field that required it.
• This would need just loop through each field in the form and check for data.
• Data Format Validation - Secondly, the data that is entered must be checked for correct
form and value.
• This would need to put more logic to test correctness of data.
• Example:
• Email validation: check presence of @ and period (.) in the input
• Check correctness of numeric field
• Check valid age: negative value for age
The try...catch...finally Statement:
• JavaScript implements the try...catch...finally construct as well as the throw operator to handle
exceptions.
• We can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript
syntax errors.
• try...catch...finally block syntax:
<script type="text/javascript">
try {
// Code to run
[break;]
} catch ( e ) {// Code to run if an exception occurs
[break;]
} finally {
// Code that is always executed regardless of an exception occurring
}
</script>
• The try block must be followed by either exactly one catch block or one finally block (or one of both).
• When an exception occurs in the try block, the exception is placed in e and the catch block is
executed.
• The optional finally block executes unconditionally after try/catch.
• The throw Statement:
• You can use throw statement to raise to built-in exceptions or we customized exceptions. Example: division by zero
function myFunc()
{
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}else{
var c = a / b;
}
}catch ( e ) {
alert("Error: " + e );
}
}