WebP Chapter 4 JavaScript
WebP Chapter 4 JavaScript
(CoSc3031)
Web Programming
2
Unit Objectives
Web Programming 3
Introduction to Scripting
Scripting Languages are mainly used to build the programming
environment in HTML document
Make Web pages dynamic and interactive.
Some languages are : VBScript, JavaScript, Jscript, PHP, Python, Active
Server Page(ASP), Java Server Page(JSP), Java Server Face(JSF),
Common Gateway Interface(CGI), Perl , Java Servlets, etc.
Browser Includes Scripting Interpreter
Choosing a Scripting Language
Browser compatibility
Programmer familiarity
Scripts can be executed on client or the server.
Web Programming
4
Introduction to scripting & classification
1. Client-Side Scripting
Client-side scripting enables interaction within a webpage.
The code required to process user-input is downloaded and
compiled by the browser or plug-in.
It is a language that runs on a local browser (on the
client tier) instead of on a Web server (on the
processing tier)
An example of a client-side interaction is a rollover
(typically triggered when choosing a navigation option).
Web Programming
5
Introduction to scripting classification
2. Server-Side Scripting
Refers to a scripting language that is executed from a
Web server
Used to develop more interactive Web sites
Is easy to learn
Includes object-oriented programming capabilities
Supports many types of databases (MySQL, Oracle, Sybase, ODBC-
compliant
Source code is visible to the user. Source code is not visible to the user
because the output of server side program
is an HTML page.
Used for validations and Used for business logic and data access
functionality for the user events. from the database. The pages are created
dynamically.
Depends on the browser and Not depend on the client, any server side
version. technology can be used.
E.g.. JavaScript, VBscript etc E.g. PHP, Python, Ruby, JSP, Perl etc
Web Programming 7
Client-Side Programming
Client-side scripts are placed within an HTML document in the
user’s web browser rather than the web server to allow greater
interactivity in a document. For example – client-side scripting
could check the user’s form for errors before submitting it
Enables web pages to change content according to user input and
other variables, including the time of day. Can also be stored in a
separate file that is referenced to the documents that use it.
HTML is good for developing static pages(static web sites)
can specify text/image layout, presentation, links, …
Web page looks the same each time it is accessed
in order to develop interactive/reactive pages, must integrate
programming in some form or another
Web Programming
8
Client Based Processing
Web Programming
9
Applications of Client-Side Scripting
Web page responds to or reacts directly with user interaction
through HTML Form elements, eg, input fields, text areas,
buttons, radio buttons, etc.
Distributing a small amount of database information directly
from the Web page
You need to control the Web page appearance based on user
selections
You want to preprocess data before submission to the server.
Web Programming
10
Server-Side Programs
a user must be connected to the Web server to run the server-
side script
only the programmer can create or alter the script
the system administrator has to be concerned about users
continually accessing the server and potentially overloading the
system
A server-side language is one that runs on the Web server.
Examples: PHP, Python, JSP, ASP, CGI, Perl, …
Web Programming 11
Server Based Processing
Server
User’s Input Processing
Web Programming
12
Introduction to JavaScript
A client-side scripting language that allows Web page authors to
develop interactive Web pages and sites
JavaScript is considered a scripting language because it is
interpreted by the browser at runtime (when the web page is
actually opened) rather than compiled and stored on your
computer.
It provides a computational capability in web documents.
It is used in creating, accessing, modifying a document.
Used in most Web browsers including Firefox and Internet
Explorer
Web Programming
13
Introduction to JavaScript …
JavaScript scripting language
Easy Program development
Easy Program control structure
Client-side scripting enhances functionality and appearance
Makes pages more dynamic and interactive
Pages can produce immediate response without contacting
a server
Customization is possible on the basis of users’ explicit
and implicit input
Browser has to have a built-in (JavaScript) interpreter
Web Programming
14
Introduction to JavaScript …
JavaScript is an interpreted programming or script language
from Netscape.
Created by Netscape
Originally called Mocha, LiveWire then LiveScript, now
JavaScript
JavaScript is used in Web site development to such things as:
automatically change a formatted date on a Web page
cause a linked-to-page to appear in a popup window
cause text or a graphic image to change during a mouse
rollover
Web Programming
15
What can JavaScript do?
Giving the user more control over the browser
Detecting the user's browser, OS, screen size, etc.
Performing simple computations on the client side
Validating the user's input
Handling Events, Errors and exceptions
Generating HTML pages on-the-fly without accessing the
Web server.
Web Programming
16
Client-side Script can’t ...
Set or retrieve browser preferences
launch an application on client computer
read or write files on client computer
Extract text content from HTML page
Do much of anything on server computer including
accessing a database
Web Programming
17
How Does It Work?
Embedded within HTML page
View source
Executes on client
Fast, no connection needed once loaded
Simple programming statements combined with HTML
tags
Interpreted (not compiled)
No special tools required
Web Programming
18
Features of JavaScript
Designed for programming user events JavaScript is a lightweight,
interpreted language
Embedded within HTML, Complementary to and integrated with
HTML.
Minimal Syntax- Easy to learn
Mainly used for client side scripting because it is supported by all
the browsers.
Open source-free
Platform Independence/ Architecture Neutral
Web Programming
19
JavaScript – lexical structure
JavaScript is object based, action-oriented, &object orientation .
JavaScript is case sensitive.
A semicolon ends a JavaScript statement
C-based language developed by Netscape
Comments
Supports single line comments using //
and multi line comments using /*…..*/
Web Programming
20
JavaScript – lexical structure …
The Web browser runs a JavaScript program when the Web
page is first loaded, or in response to an event.
JavaScript programs can either be placed directly into the
HTML file or they can be saved in external files.
placing a program in an external file allows you to hide
the program code from the user
source code placed directly in the HTML file can be
viewed by anyone
Web Programming
21
JavaScript – lexical structure …
A JavaScript program can be placed anywhere within the
HTML file.
Many programmers favor placing their programs between
<head> tags in order to separate the programming code
from the Web page content and layout.
Some programmers prefer placing programs within the body
of the Web page at the location where the program output is
generated and displayed.
Web Programming
22
Using the <script> Tag
To embed a client-side script in a Web page, use the
element:
<script type=“text/javascript” >
script commands and comments
</script>
To access an external script, use:
<script src=“url” type=“text/javascript”>
script commands and comments
</script>
<SCRIPT LANGUAGE=“JavaScript”>
-----
(JavaScript code goes here)
----
</SCRIPT>
Web Programming
23
JavaScript as a referenced file
3 Ways of Using JavaScript in HTML
Embedded
External file
Inline
Embedded
Embedding JavaScript code into an html page using <script> tag.
Embedded code is not accessible from other pages.
External file
Enables a JavaScript script stored in a separate file to be included as part of
the current page.
The important use of the referenced file is
Reusable function can be placed in the .js file.
Multiple pages can use the same .js file.
Maintains will be easier.
Web Programming
24
External and Inline JavaScript
Can be achieved by using the SRC attribute of the <script> tag.
External Javascript file should have an extension .js
Should not use <script> tag inside the .js file
For example:
<script language=“JavaScript” src=“external.js”>
</script> <!– should have the closing </script> tag -->
Inline JavaScript
Scripts are included inside the HTML tag.
<html>
<body onLoad="alert('document loaded')";>
<h1>Inline JavaScript</h1>
<input type="button" name="but1" value="click"
onClick="window.close()">
</body></html>
Web Programming 25
JavaScript-Example 1
<html> directs the document object to
<head> write the given string
<script language=“JavaScript”>
document.write (“<b> This is first </b>”);
</script>
</head>
<body>
Now where does this print on the web page???? <br />
<script language=“JavaScript”>
document.write ( “This might be last?”)
</script>
</body>
</html>
Web Programming
26
JavaScript-Example 2
Now, let JavaScript generate HTML for us…
<html>
<head><title>JavaScript HelloWorld!</title></head>
<body>
<script laguage="JavaScript">
document.write("<h2>Javascript-Generated
output:</h2> <p>This paragraph generated by
JavaScript</p>
<p>It can even insert an image</p>
<img src='../assigns/RayWeb/images/cathedral.jpg' />")
</script>
</body>
</html>
Web Programming
27
JavaScript –Variables
Declared using the keyword var. Declaring variables is not mandatory.
Must start with a letter or an underscore and can have digits.
Does not have explicit data types.
The Data type is automatically decided by the usage.
Scope is by default global. If a variable is prefixed by the keyword “var”
within a function then it is a local variable.
The formal parameters are local to the function.
function demo()
{
var inum1 = 10; // Local to the function
inum2 = 20; // Global to the document.
}
demo(); // Invoking function
inum1 = inum1+1; //Error because inum1 is local variable
inum2 = inum2+1; // no Error
Web Programming
28
JavaScript – Implicit data types
JavaScript recognizes the following implicit data types
a. Number e.g. var x=12.5;
b. String e.g. var x==“any text”;
c. Boolean e.g. var x=true;
d. Object e.g. var x={key:’value’}
e. Array e.g. var x={1, 2, “text”};
f. The special value null e.g. var x=null;
a. Type conversion
JavaScript automatically converts between data types
Consider
Web Programming
30
Special operators
typeof operator
Unary operator
Indicates the data type of the operand.
Eg
x=123;
alert(typeof(x)); // Number
x="Hello"
alert(typeof(x)); //
String
new
Used for instantiation of objects.
Eg: today = new Date( )
this
used to refer to the current object
Web Programming
31
JavaScript -Simple Interactions
alert
Displays an Alert dialog box with a message and an OK button.
Syntax: alert("message");
Example: alert(“You’re in a Special Area …”);
alert(“count=“+count); // count is a variable to be traced here
confirm
Displays a Confirm dialog box with the specified message and OK
and Cancel buttons.
Syntax: confirm("message");
Example: ans = confirm(“Are you sure you want to continue?”);
ans will be true if OK is clicked or false if Cancel is clicked
Web Programming
32
JavaScript -Simple Interactions …
eval
The eval function evaluates a string and returns a value.
Syntax: eval(stringExpression)
Example: eval(1+2*3) // gives 7 here
prompt
The prompt function prompts for a string value.
Syntax: prompt(“message”) or prompt(“message”, default value)
Example:
aString1 = prompt(“Enter Name”);
aString2 = prompt(“Enter Salary”, 0);
Note: The return value is a string. Need to convert if a numeric value is desired.
Use parseInt() or parseFloat().
Example: numSalary = parseInt(aString2);
numSalary = numSalary + 500;
Web Programming
33
JavaScript-Exercise 1
Create a web page that contains
A title of “My first JavaScript Page”
A Javascript to ask the user for their name
A personalized welcome message to the user.
Web Programming
34
JavaScript – Control structures
Control structure in JavaScript, as follows:
if
Is used to conditionally execute a single block of code
if .. else
a block of code is executed if the test condition evaluates to a boolean
true else another block of code is executed.
switch …. case
switch statement tests an expression against a number of case options
executes the statements associated with the first match.
Web Programming
35
JavaScript – Loop
while loop
The while statement is used to execute a block of code while a certain
condition is true
Syntax : while ( test condition)
{
zero or more statements
}
for loop
Iterate through a block of statements for some particular range of values
Syntax : for(initstmt; condstmt; updstmt ){
zero or more statements
}
do while loop
block of statements is executed first and then condition is checked
Syntax : do
{
zero or more statements
}while ( test condition)
Web Programming
36
JavaScript – Control structures
break
Terminates the current loop, switch, or label statement and transfers
program control to the statement following the terminated loop.
continue
In contrast to the break statement, continue does not terminate the
execution of the loop entirely.
In a for loop, it jumps to the update expression.
In a while loop, it jumps back to the condition.
for(i=0; i<5; i++)
{
inner : /*JS Comments : label */
for(j=0;j<5;j++)
{
if(i==j){ break inner;}
document.write(j+" ");
}
document.write("<br>");
}
Web Programming
37
JavaScript Functions
Key issues about using functions
Naming functions
Passing in parameters
Using local variables within functions
How to call (i.e., invoke) functions
How to handle a function’s return value
Where to put JS functions in your webpage
Web Programming
38
JavaScript Functions – Basic Principles
Reasons to use functions
Ease of communication
Problem simplification
Easier construction
Code readability
Reusability
Maintainability
Web Programming
39
JavaScript Functions -User defined
A function is a block of code that has a name.
Way to organize your code. User can write his/her own functions
JavaScript functions is to link actions on a web page with the JavaScript code.
JavaScript has some in-built functions.
To create a function you define its name, any values ("arguments"), and some
statements:
function myfunction(argument1,argument2,etc)
{
some statements;
}
Web Programming
40
More user defined functions
JavaScript functions can return any value and explicit return type is not used in
JavaScript.
Web Programming
41
More User defined Functions
/* Function to validate an email id
name : checkEmail()
parameter : String (email id)
returns : true(success), false ( fail)*/
function checkEmail(email){
/* checking for the length */
if(email.length<=0) {
return false;
}
/* checking the occurance of @ */
if(email.indexOf("@")==-1) {
return false;
}
return true;}
Web Programming
42
JavaScript Functions - Built-in
Built-In Functions
Prompt
Alert
Confirm
Web Programming
43
Other Top-Level functions
eval
Evaluates a string of JavaScript code without reference to a particular
object.
Syntax eval( string)
parseInt and parseFloat
Return a numeric value when given a string as an argument.
Syntax parseInt( string) , Syntax
parseFloat( string)
isNaN
Evaluates an argument to determine if it is “NaN” (not a number).
Syntax isNaN( testValue)
isFinite
evaluates an argument to determine whether it is a finite number
Syntax isFinite( number)
Number and String
functions let you convert an object to a number or a string.
Web Programming
44
JavaScript Function-Example
<script langauge="JavaScript">
<!-- hide me
function announceTime( ) {
// show me -->
</script> </head> <body> ... </body> </html>
Web Programming
45
JavaScript Function in Action ...
FORMS
function IsFormComplete(FormName)
{ var x =0
var FormOk = true
Web Programming
47
Using Arrays, syntax
An array is an ordered collection of values referenced by a
single variable name.
The syntax for creating an array variable is:
var variable = new Array(size);
variable is the name of the array variable
size is the number of elements in the array (optional)
To populate the array with values, use:
variable[i]=value;
where i is the ith item of the array. The 1st item has an index
value of 0.
Web Programming
48
Array ways
In general, you can create array in three different ways in JavaScript. The syntax is:
1. arrayName = new Array(arrayLength);
2. arrayName = new Array(element0, element1, ..., elementN);
3. arrayName = [element0, element1, ..., elementN];
Access an Array
document.write(planet); // Display all elements
document.write(planet[4]); // 4th element of array
for (var i=0; i < myArray1.length; i++) {
document.write(planet[i] + "<BR>");
}
Array Object Methods
array.concat(array2) toString()
array.sort([compareFunction]) reverse();
pop() filter()
push(value) join(separator)
reverse() shift()/unshift adding/removing to/from front
Sort()
49 Web Programming
Arrays: Example
<body>
<script language="JavaScript">
function arrayFunction() {
var grade = new Array("70", "60", "80", "90", "20");
document.write("<br> Popped: " + grade.pop());
grade.reverse();
document.write("<br>Reversed: ");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);
document.write("<br>Converted to string: " + grade.toString());
</script>
</head>
<body onLoad="arrayFunction();">
</body>
50 Web Programming
Using Arrays …
Methods Description
Web Programming 51
Objects
JavaScript is based on object-based paradigm.
Once instantiated, the properties and methods of the object can be used
accordingly.
Web Programming
52
Creating objects
Using keyword new
Any Object should be instantiated before being used.
Once instantiated, the properties and methods of the object can be used
accordingly.
Example
var newDateObj = new Date();
alert(“Today Date is :” +
newDateObj.getDate());
alert(“And the Month is :” +
newDateObj.getMonth());
Web Programming
53
Example- Window Object methods
(Dialog boxes )
Alert dialog box - alert( message)
Takes in a string argument and displays an alert box.
Web Programming
54
Window Objects
window - the current browser window
window.history - the Netscape history list
window.document - the html document currently in the
browser client area
window.location - the browser location field
window.toolbar - the browser toolbar
window.document.link - an array containing all of the links in
the document
window.document.anchor - an array of all the anchor points in
the document
Web Programming
55
Window Objects (more…)
Window.document.layer - a named document layer
window.document.applet - a named java applet area
window.document.image- a named image tag
window.document.area - a named area
window.document.form - a named form or the default form
ect, ect
Web Programming
56
Generally: -Object Hierarchy
window
password submit
Web Programming
57
JavaScript Event Handling
Events are occur usually as a result of some action by the user/system.
With an event handler you can do some action when an event occurs.
Web Programming 58
Events and Functions
Many event handlers are supported
onmouseover, onmouseout, onclick
…/swap image.html
Web Programming
59
JavaScript: Form 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. But how can you be certain that a valid input was
filled by the user? With the help of JavaScript the form input
can easily be checked before sending it over the Internet. It is
sent only if the input is valid.
form validation may be:
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?
60 Web Programming
JavaScript Events and HTML Forms
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript>
function changecolor()
{
document.bgColor="#ff0000";
}
</HEAD>
<BODY>
FORM >
<INPUT TYPE=“button” VALUE="Click Me"
onclick="changecolor()">
</FORM>
</BODY></HTML>
Web Programming
61
JavaScript Events and HTML Forms …
Form Object
Window.document.form
A form is a property of the document but is also an object
Form elements are properties of a form and are also objects
Access to form’s properties is done through the NAME
attribute of the FORM tag
Access to the properties of the form elements is done through
the NAME attributes of the particular form element
Web Programming
62
JavaScript Events and HTML Forms …
Methods
Behavior associated with an object
Essentially functions that perform an action
Some are built in and others user made
Built-In Methods of the window object
Confirm
Alert
Prompt
Web Programming
63
JavaScript Events and HTML Forms …
User Events
An event occurs when a user makes a change to a form element
Ex. Click a button, mouseover an image
Detection of an event done by event handlers
Event handler is an attribute of the HTML button
<form>
<input type=button value=“please click” onclick=“function name()”>
</form>
Web Programming
64
Example
65 Web Programming
Example: a script that creates and validates the above form:
<html> alert("Email oK!");
<head> if(form.urmessage.value=="")
alert("No message written");
<script language="JavaScript">
else
function check(form) alert("Message ok");
{ }
if (form.urname.value == "") </script>
</head
alert("Please enter a string as your name!")
<body>
else <h2> <u> Form validation </u> </h2>
alert("Hi " + form.urname.value + "! Name ok!"); <form name="first">
if(form.age.value < 0 || form.age.value=="") Enter your name: <input type="text"
name="urname"> <br>
alert("Age should be number and greater than 0");
Enter your age: <input type="text" name="age">
else <br>
alert("Age ok"); Enter your e-mail address: <input type="text"
if (form.email.value == "" || name="email"> <br>
form.email.value.indexOf('@', 0) == -1) write message: <textarea name="urmessage"
cols=40 rows=10></textarea><br><br>
alert("No valid e-mail address!");
<input type="button" name="validate"
else value="Check Input" onClick="check(this.form)">
</body>
</html>
66 Web Programming
JavaScript Events Example
<HTML> //--></SCRIPT>
<HEAD> </HEAD>
<SCRIPT LANGUAGE=JavaScript><!-- <BODY BGCOLOR="#FFFFCC">
<P><FORM name=addmult>
function plus(){
<P>Enter a number in each field:
var n1; var n2;
<INPUT TYPE=text NAME=num1 VALUE=""
n1=document.addmult.num1.value; SIZE=5>
n2=document.addmult.num2.value; <INPUT TYPE=text NAME=num2 VALUE=""
SIZE=5><BR>
n1=parseFloat(n1);
<INPUT TYPE=button VALUE="+"
n2=parseFloat(n2); onclick="plus()">
document.addmult.result.value=n1+n2; } <INPUT TYPE=button VALUE="*"
function times(){ onclick="times()"><BR>
<INPUT TYPE=reset VALUE="Reset Form"><BR>
var n1; var n2;
<TEXTAREA NAME=result ROWS=3 COLS=27
n1=document.addmult.num1.value; WRAP=virtual></TEXTAREA>
n2=document.addmult.num2.value; </FORM>
n1=parseFloat(n1); </BODY>
n2=parseFloat(n2); </HTML>
document.addmult.result.value=n1*n2; }
Web Programming
67
JavaScript-Exercise
In this exercise, you will:
-- use css & a table to create a menu bar
-- handle “onmouseover” events
-- display information in an alert
-- update the window.status
-- create & call 2 functions
-- work with several Math Methods
Web Programming
68
JavaScript-Exception handling
Exception handling in JavaScript is almost the same as in
Java throw expression creates and throws an exception
The expression is the value of the exception, and can be of any type
(often, it's a literal String)
• try {
statements to try
}
• catch (e) { // Notice: no type declaration for e
exception-handling statements
}
• finally { // optional, as usual
code that is always executed
}
With this form, there is only one catch clause
Web Programming
69
JS-Exception handling …
• try { statements to try
}
• catch (e if test1) {
exception-handling for the case that test1 is true
}
• catch (e if test2) {
exception-handling for when test1 is false and test2 is true
}
• catch (e) {
exception-handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
Typically, the test would be something like
e == "InvalidNameException“ Web Programming
70
JS DOM
The DOM (Document Object Model) gives generic access to most elements, their
styles and attributes in a Web document. Each HTML document loaded into a
browser window becomes a Document object handled by the browser. It is a
language to access, modify and manipulate web content objects. The DOM
structure is:
71 Web Programming
State maintenance in JavaScript: Cookie
A cookie is a small file that the server embeds on the
user's computer. Each time the same computer
requests for a page with a browser, it will send the
cookie too. With JS, you can both create and retrieve
cookie values.
Cookies are a mechanism for storing data in the remote browser
and thus tracking or identifying return users.
It is user controled and act as local storage.
72 Web Programming
JS 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.
73 Web Programming
How It Works?
Cookies are a plain text data record of 5 variable-length fields:
Expires: The date the cookie will expire. If this is blank, the
cookie will expire when the visitor quits the browser.
Domain: The domain name of your site.
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.
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.
Name=Value: Cookies are set and retrieved in the form of key-
value pairs.
74 Web Programming
How It Works? …
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
75 Web Programming
How to Creating, & Storing Cookie
Storing Cookies:he 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";
This sets a cookie named "uname" - that expires after ten hours.
<script>
setcookie("uname", $name, time()+36000);
</script>
<html> <body> …
76 Web Programming
Thank You