Internet Programming II - 1-JavaScript
Internet Programming II - 1-JavaScript
JavaScript
Outline
1. Introduction
2. Basic Language Features: variables, expressions,
operators, statements
3. Javascript: Basic syntax and flow control statements
4. Javascript : Forms and Functions
5. Javascript : Arrays and Objects
6. Javascript :Error and Event Handling
7. Javascript :Document Object Model (DOM)
8. Advanced concepts of Client-side scripting
2 Internet Programming-I
Unit Objectives
3 Internet Programming-I
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.
4 Internet Programming-I
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).
5 Internet Programming-I
Introduction to scripting classification
2. Server-Side Scripting
Refers to a scripting language that is executed from a
Web server
Used to develop interactive Web sites
Is easy to learn
Includes object-oriented programming capabilities
Supports many types of databases (MySQL, Oracle, Sybase, ODBC-
compliant
6 Internet Programming-I
Scripting language
Client Side Scripting Server Side Scripting
Runs on the user’s computer Runs on the Web server
i.e. Browser interprets the script.
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 E.g. PHP, Python, Ruby, Perl etc
Internet Programming-I
7
Client-Side Programming
HTML is good for developing static pages
can specify text/image layout, presentation, links, …
Web page looks the same each time it is accessed
8 Internet Programming-I
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
9
Internet Programming-I
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
10 Internet Programming-I
Introduction to JavaScript
JavaScript scripting language
Enhances functionality and appearance
Client-side scripting
Makes pages more dynamic and interactive
Foundation for complex server-side scripting
Program development
Program control
11 Internet Programming-I
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
12 Internet Programming-I
Introduction to JavaScript
JavaScript scripting language
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
Foundation for complex server-side scripting
13 Internet Programming-I
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.
14 Internet Programming-I
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
15 Internet Programming-I
Features of JavaScript
An interpreted language
Embedded within HTML
Minimal Syntax- Easy to learn
Mainly used for client side scripting because it is supported by
all the browsers.
Designed for programming user events
Platform Independence/ Architecture Neutral
16 Internet Programming-I
JavaScript – lexical structure
JavaScript is object based and action-oriented.
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 /*…..*/
17 Internet Programming-I
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
18 Internet Programming-I
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.
19 Internet Programming-I
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>
20 Internet Programming-I
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.
21 Internet Programming-I
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>
22
Internet Programming-I
Comments in JavaScript
The syntax for a single-line comment is:
// comment text
The syntax of a multi-line comment is:
/*
comment text covering several lines
*/
23 Internet Programming-I
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>
24 Internet Programming-I
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>
25 Internet Programming-I
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
26 Internet Programming-I
JavaScript – Implicit data types
JavaScript recognizes the following implicit data types
a. Number
b. String
c. Logical
d. Object
e. The special value null
a. Type conversion
JavaScript automatically converts between data types
Consider
27 Internet Programming-I
JavaScript – Operators
Arithmetic Operators
+, ++, -, --, *, /, %
Relational Operators
==, !=, ===, !==, >, >=, < , <=
Logical Operators ( and , or , not)
&&, ||, !
Assignment Operators
=, +=, -=, *=, /=, %=
Strict equal (===)
Returns true if the operands are equal and of the same type.
Strict not equal (!==)
Returns true if the operands are not equal and/or not of the same
type.
28 Internet Programming-I
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
29 Internet Programming-I
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
30 Internet Programming-I
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;
31 Internet Programming-I
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.
32 Internet Programming-I
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.
33 Internet Programming-I
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)
34 Internet Programming-I
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>");
}
Internet Programming-I
35
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
36 Internet Programming-I
JavaScript Functions – Basic Principles
Reasons to use functions
Ease of communication
Problem simplification
Easier construction
Code readability
Reusability
Maintainability
37 Internet Programming-I
JavaScript Functions -User defined
A function is a block of code that has a name.
Way to organize your code. User can write his 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;
}
38 Internet Programming-I
More user defined functions
JavaScript functions can return any value and explicit return type is not used in
JavaScript.
39 Internet Programming-I
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;}
40 Internet Programming-I
JavaScript Functions - Built-in
Built-In Functions
Prompt
Alert
Confirm
41 Internet Programming-I
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.
42 Internet Programming-I
JavaScript Function-Example
<script langauge="JavaScript">
<!-- hide me
function announceTime( ) {
// show me -->
</script> </head> <body> ... </body> </html>
43 Internet Programming-I
JavaScript Function in Action
ROLLOVER BUTTONS
44 Internet Programming-I
JavaScript Function in Action
INPUT-TEXT FIELD
45 Internet Programming-I
JavaScript Function in Action
FORMS
function IsFormComplete(FormName)
{ var x =0
var FormOk = true
47 Internet Programming-I
Using Arrays
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.
48 Internet Programming-I
Using Arrays …
Methods Description
push( element1, ..., Add / removes the last element to/from an array
elementN) and returns that element.
49 Internet Programming-I
Objects
JavaScript is based on object-based paradigm.
Once instantiated, the properties and methods of the object can be used
accordingly.
50 Internet Programming-I
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());
51 Internet Programming-I
Example- Window Object methods
(Dialog boxes )
Alert dialog box - alert( message)
Takes in a string argument and displays an alert box.
52 Internet Programming-I
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
53 Internet Programming-I
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
54 Internet Programming-I
Generally: -Object Hierarchy
window
password submit
55 Internet Programming-I
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.
56 Internet Programming-I
Events and Functions
Many event handlers are supported
onmouseover, onmouseout, onclick
…/swap image.html
57 Internet Programming-I
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>
58 Internet Programming-I
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
59 Internet Programming-I
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
60 Internet Programming-I
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>
61 Internet Programming-I
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; }
62 Internet Programming-I
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
63 Internet Programming-I
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
64 Internet Programming-I
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
65
e == "InvalidNameException“
Internet Programming-I
Thank You