Upload
lyliem
View
221
Download
1
Embed Size (px)
Citation preview
Chapter 4:-
JavaScript
Compiled By:- Sanjay Patel
Assistant Professor,
SVBIT.
JavaScript is a scripting language.
A JavaScript consists of lines of executable computer code.
A JavaScript is usually embedded directly into HTML
pages.
JavaScript was designed to add interactivity to HTML
pages.
JavaScript is free. Everyone can use JavaScript without a
license.
A scripting language is a lightweight programming
language.
Introduction
Sanjay Patel
The client side scripting is a class of scripting language that are
used on the client machine in the user‟s web browser.
The client side scripting allows to change the content of the web
page depending upon the user input.
For example:- on clicking the button some message should be
displayed.
JavaScript is about "programming" the behavior of a browser.
This is called client-side scripting (or browser scripting).
Server-side scripting is about "programming" the
behavior of the server (ASP/PHP/JSP).
Client Side – Server Side
Sanjay Patel
Java Java Script
Requires the JDK to create the
applet
Requires a text editor
Requires a Java virtual machine to
run the applet.
Required a browser that can
interpret JavaScript code
Applet files are distinct from the
XHTML code.
JavaScript can be placed within
HTML and XHTML.
Source code is hidden from the user. Source code is made accessible to
the user
Programs must be saved as
separate files and compiled before
they can be run.
Programs cannot write content to the
hard disk.
Programs run on the server side. Programs run on the client side.
Difference between Java and Java Script
Sanjay Patel
More Differences
Sanjay Patel
Java Java Script
Java is a programming Language Java script is a scripting Language
Java is a Object Oriented programming
Language
Java Script is not a object oriented
programming Language. It is object model
is far different than a typical object
oriented programming language such as
C++ or Java.
Java is strongly typed language and the
type checking is done at compile time
In Java Script variables need not be
declared before their use. Checking the
compatibility of type can be done
dynamically.
Object in java are static. That means the
number of data members and method are
fixed at compile time.
In JavaScript the objects are dynamic. That
means we can change the total data
members and method of an object during
execution.
JavaScript is executed on the client side
This means that the code is executed on the user's
processor instead of the web server thus saving
bandwidth and strain on the web server.
JavaScript is a relatively easy language
The JavaScript language is relatively easy to learn
and comprises of syntax that is close to English.
Advantages of JavaScript
Sanjay Patel
JavaScript is relatively fast to the end user
As the code is executed on the user's computer, results
and processing is completed almost instantly
depending on the task (tasks in JavaScript on web
pages are usually simple so as to prevent being a
memory hog) as it does not need to be processed in
the site's web server and sent back to the user
consuming local as well as server bandwidth.
Cont‟d..
Sanjay Patel
Versatility
JavaScript plays nicely with other languages and
can be used in a huge variety of applications.
Unlike PHP or SSI scripts, JavaScript can be inserted
into any web page regardless of the file extension.
JavaScript can also be used inside scripts written in
other languages such as Perl and PHP.
Cont‟d..
Sanjay Patel
Security
Because the code executes on the users„ computer, in some
cases it can be exploited for malicious purposes. This is
one reason some people choose to disable JavaScript.
Reliance on End User
JavaScript is sometimes interpreted differently by
different browsers. Whereas server-side scripts will
always produce the same output, client-side scripts can be
a little unpredictable. Don't be overly concerned by this
though - as long as you test your script.
Disadvantages
Sanjay Patel
Unlike HTML, JavaScript is case sensitive.
Dot Syntax is used to combine terms.
e.g ., document.write("Hello World")
Certain characters and terms are reserved.
JavaScript is simple text (ASCII).
Java script Syntax
Sanjay Patel
First way is to embedded it directly within the
<script> and </script> tag pair
The <script> tag notifies the browser that
everything contained within is script and is to be
interpreted by suitable interpreter.
<script language=“javascript”>
Javascript code
</script>
Two ways to insert JS Code
Sanjay Patel
Scripts in HTML must be inserted between <script> and
</script> tags.
Scripts can be put in the <body> and in the <head>
section of an HTML page.
The <script> and </script> tells where the JavaScript
starts and ends.
Java Script in HTML
Sanjay Patel
<html>
<body>
<h1>My First Web Page</h1>
<script language=“JavaScript”>
document. write("<p>My First JavaScript</p>");
</script>
</body>
</html>
Cont‟d..
Sanjay Patel
Second way to insert JS code is to place and
external source file and refer to it from an HTML
file.
This external source file generally has the extension
.js. A source file contains only JavaScript statements
without any script tag or other HTML tags
<script language=“javascript” src=“source.js”>
Javascript code
</script>
Second ways to insert JS Code
Sanjay Patel
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>
Using the <script> Tag
Sanjay Patel
First JavaScript Program
Sanjay Patel
Adding Comment
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
Methods are actions applied to particular objects.
Methods are what objects can do.
e.g., document.write(”Hello World")
document is the object.
write is the method.
Methods
Sanjay Patel
Properties are object attributes.
Object properties are defined by using the object's
name, a period, and the property name.
e.g., background color is expressed by:
document.bgcolor .
document is the object.
bgcolor is the property.
Properties
Sanjay Patel
Java scrip offers the very same programming
capabilities found in most programming languages.
Creating variables, constants, programming
constructs, user defined functions and so on.
These are the techniques that makes the java script
the exciting programming language that extends
the functionality of HTML and makes web pages
interactive
Basic Programming Technique
Sanjay Patel
The <head> … </head> tag make an ideal place
to create JavaScript variables and constants and so
on.
This is because the head of an HTML document is
always processed before the body.
By using this technique the interpreter will always
create functions, constants of structure before using
them.
Basic Programming Technique
Sanjay Patel
It is important because any attempt to use a
variable or any object before it is defined, results in
an error.
Variable name can begin with upper case or
lowercase or underscore character or dollar sign
character.
The remaining characters can consist of letters, or
underscore or digits.
Variable names are case sensitive.
Basic Programming Technique
Sanjay Patel
The dollar sign ($) character is reserved for
machine generated code and should not be used
in scripts.
Point to be Remember
Sanjay Patel
There are following types used in Java Script
String
Number
Boolean
Null & Undefined.
Object
Array
Data Types
Sanjay Patel
Variables contain values and use the equal sign to
specify their value.
Variables are created by declaration using the var
command with or without an initial value state.
e.g. var month;
e.g. var month = “April”;
Variable
Sanjay Patel
Which one is legal?
Sanjay Patel
My_variable
$my_variable
1my_example
_my_variable
@my_variable
My_variable_example
++my_variable
%my_variable
#my_variable
~my_variable
myVariableExample
Legal
Illegal
Keyword
Sanjay Patel
Local variables are declared with in a function.
Syntax:- var name_of_variable=value;
The keyword var specifies the variable is a local
variable and visible within the scope in which it is
declared
var total=0 //number
var message=“Hello”; //string
var found=false; //boolean
Local Variable
Sanjay Patel
A string is a variable which stores a series of
characters like “MCA Dept.".
A string can be any text inside quotes. You can use
simple or double quotes:
var carname="Volvo XC60";
var carname='Volvo XC60';
Strings
Sanjay Patel
You can use quotes inside a string, as long as they
don't match the quotes surrounding the string.
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Cont‟d..
Sanjay Patel
The + operator can also be used to add string
variables or text values together.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
“What a verynice day”
Concatenation
Sanjay Patel
JavaScript has only one type of numbers. Numbers
can be written with, or without decimals.
var x1=34.00; //Written with decimals
var x2=34; //Written without decimals
Extra large or extra small numbers can be written
with scientific (exponential) notation:
var y=123e5; // 12300000
var z=123e-5; // 0.00123
Number
Sanjay Patel
Booleans can only have two values: true or false.
var x=true
var y=false
Booleans are often used in conditional testing.
Boolean
Sanjay Patel
Undefined is the value of a variable with no value.
Variables can be emptied by setting the value to
null;
cars=null;
person=null;
Null
Sanjay Patel
An object is delimited by curly braces. Inside the
braces the object's properties are defined as
name and value pairs (name : value).
The properties are separated by commas:
var person={firstname:"John",
lastname:"Doe“, id:5566};
Object
Sanjay Patel
The object (person) in the example Below has 3
properties: firstname, lastname, and id.
Spaces and line breaks are not important. Your
declaration can span multiple lines:
var person={ firstname : "John“, lastname : "Doe“,
id : 5566 };
Object
Sanjay Patel
Arithmetic
Assignment
Concatenation
Comparison
Logical
Conditional
Operator
Sanjay Patel
Arithmetic operators are used to perform arithmetic
between variables and/or values.
Arithmetic
Sanjay Patel
Operator Name Description Example
+ Addition Adds the operands 3 + 5
- Subtraction Subtracts the right operand from the left operand
5 - 3
* Multiplication Multiplies the operands 3 * 5
/ Division Divides the left operand by the right operand
30 / 5
% Modulus Calculates the remainder 20 % 5
Arithmetic Operator
Sanjay Patel
Given that y=5, the table below explains the
arithmetic operators:
Example Of operator
Sanjay Patel
Output
Sanjay Patel
Cont‟d..
Sanjay Patel
Example Result
var result = 2 + 3; 5
result = “Hello” + “ World “; Hello World
result = 2 + “ MB “; 2MB
result = “P” + “ 4 “; P4
result = “Y” + 2 + “ K “; Y2K
result = 2 + 3 + “ K “; (2+3) + “K” = 5K
result = “K” + 2 + 3; (“K”+2) +3 = K23
result = “Age:” + 32 + “<br>”; Age: 32 <br>
Assignment operators are used to assign values to
JavaScript variables.
Given that x=10 and y=5, the table below
explains the assignment operators:
Assignment
Sanjay Patel
Comparison operators are used in logical statements to determine
equality or difference between variables or values.
Given that x=5, the table below explains the comparison
operators:
Comparison
Sanjay Patel
Comparison
Sanjay Patel
Operator Name Description Example
== Equal Perform type conversion before checking the equality
“5” == 5
=== Strictly equal No type conversion before testing “5” === 5
!= Not equal “true” when both operands are not equal 4 != 2
!== Strictly not equal No type conversion before testing nonequality 5 !== “5”
> Greater than “true” if left operand is greater than right operand 2 > 5
< Less than “true” if left operand is less than right operand 3 < 5
>= Greater than or equal
“true” if left operand is greater than or equal to the right operand
5 >= 2
<= Less than or equal
“true” if left operand is less than or equal to the right operand
5 <= 2
Operators having higher precedence are evaluated
before operators having lower precedence.
Arithmetic operator precedence
Operator Precedence
Sanjay Patel
Precedence Operators
Lowest +, -
*, /,%
Highest ++, - -
Example
Sanjay Patel
Output
Sanjay Patel
Logical operators are used to determine the logic
between variables or values.
Logical
Sanjay Patel
Operator Name Description Example
&& Logical and Evaluate to “true” when both
operands are true3>2 &&
5<2
|| Logical or Evaluate to “true when either
operand is true3>1 || 2>5
! Logical not Evaluate to “true” when the
operand is false5 != 3
Given that x=6 and y=3, the table below explains
the logical operators:
Cont‟d..
Sanjay Patel
JavaScript also contains a conditional operator that
assigns a value to a variable based on some
condition.
Syntax
variablename=(condition)?value1:value2;
Example
voteable=(age<18)?"Too young":"Old enough";
Conditional Statement
Sanjay Patel
if
if...else
if...else if....else
switch
Conditional Statements
Sanjay Patel
Very often when you write code, you want toperform different
actions for different decisions.
You can use conditional statements in your code to do this.
if statement - use this statement to execute some code only
if a specified condition is true
if...else statement - use this statement to execute some code
if the condition is true and another code if the condition is false
if...else if....else statement - use this statement to select one
of many blocks of code to be executed
switch statement - use this statement to select one of many
blocks of code to be executed
Conditional Statements
Sanjay Patel
if statement:- Use the if statement to execute some
code only if a specified condition is true.
Syntax :- if (condition)
{
code to be executed if condition is true
}
Example:- if (time<20)
{
x="Good day";
}
If Statements
Sanjay Patel
if...else statement :- Use the if....else statement to
execute some code if a condition is true and another
code if the condition is not true.
Syntax:- if (condition)
{
code to be executed if condition is true
}
else
{ code to not be executed if condition is true
}
If….else statement
Sanjay Patel
if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
Example
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
Syntax:-
switch(n)
{
case 1: execute code block 1
break;
case 2: execute code block 2
break;
default: code to be executed if n is different
from case 1 and 2
}
Switch case Statement
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
While Loop
Do… while Loop
For Loop
Looping Statements
Sanjay Patel
Syntax
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
Cont‟d..
Sanjay Patel
For loop
Sanjay Patel
For loop
Sanjay Patel
Cont‟d..
Sanjay Patel
abs()
ceil()
random()
pow()
floor()
sqrt()
Mathematical Functions
Sanjay Patel
Return the absolute value of a number:
Syntax:-
The output of the code above will be:
7.25
7.25
0
NaN
5
abs()
Sanjay Patel
Round a number upward to it's nearest integer:
Syntax:-
The output of the code above will be:
1
1
5
6
-5
-5
ceil()
Sanjay Patel
The random() method returns a random number
between 0 and 1.
Syntax:-
random()
Sanjay Patel
The pow() method returns the value of x to the
power of y (xy).
Syntax:-
The output of the code above will be:
0 1 1 27 -27 16
pow()
Sanjay Patel
The floor() method rounds a number DOWNWARDS to the
nearest integer, and returns the result.
If the passed argument is an integer, the value will not be
rounded.
Syntax:-
Output:- 0 0 5 5 5 -6 -6
floor()
Sanjay Patel
The sqrt() method returns the square root of a
number.
Syntax:-
Output:- 0 1 3 8 Nan
sqrt()
Sanjay Patel
Example of more Math Function
Sanjay Patel
Method Description Example abs( x ) absolute value of x abs( 7.2 ) is 7.2
abs( 0.0 ) is 0.0
abs( -5.6 ) is 5.6 ceil( x ) rounds x to the smallest
integer not less than x ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x
(x in radians)
cos( 0.0 ) is 1.0
exp( x ) exponential method ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906 floor( x ) rounds x to the largest
integer not greater than x floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0 log( x ) natural logarithm of x
(base e)
log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0 max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
Cont‟d..
Sanjay Patel
min( x, y ) smaller value of x and y
min( 2.3, 12.7 ) is 2.3
min( -2.3, -12.7 ) is -12.7 pow( x, y ) x raised to power y
(xy)
pow( 2.0, 7.0 ) is 128.0
pow( 9.0, .5 ) is 3.0 round( x ) rounds x to the
closest integer
round( 9.75 ) is 10
round( 9.25 ) is 9 sin( x ) trigonometric sine of
x (x in radians)
sin( 0.0 ) is 0.0
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent
of x
(x in radians)
tan( 0.0 ) is 0.0
Fig. 12.1 Math object methods.
big()
blink()
bold()
italics()
charat()
tolowercase()
touppercase()
substring()
String Functions
Sanjay Patel
The big() method is used to display a string in a
big font.
This method returns the string embedded in the
<big> tag, like this:
Syntax:-
The output of the code above will be: hello world!
big()
Sanjay Patel
The blink() method is used to display a blinking
string.
This method returns the string embedded in the
<blink> tag, like this:
Syntax:-
The blink() method only works in Firefox and
Opera.It is not supported in Internet Explorer,
Chrome, or Safari.
blink()
Sanjay Patel
The bold() method is used to display a string in bold.
This method returns the string embedded in the <b>
tag, like this:
Syntax:-
The output of the code above will be:-hello world!
bold()
Sanjay Patel
getDate()
setDate()
getHours()
setHours()
getTime()
setTime()
Date Functions
Sanjay Patel
The getDate() method returns the day of the month
(from 1 to 31) for the specified date.
Syntax:-
The output of the code above will be:
21
getDate()
Sanjay Patel
The setDate() method sets the day of the month to
the date object.
Syntax:-
The output of the code above will be:
Fri Jul 15 1983 01:15:00 GMT+0530
SetDate()
Sanjay Patel
An integer representing the day of a month.
Expected values are 1-31, but other values are
allowed:
0 will result in the last day of the previous month
-1 will result in the day before the last day of the
previous month
If the month has 31 days.32 will result in the first
day of the next month
If the month has 30 days.32 will result in the second
day of the next month
SetDate()
Sanjay Patel
The getTime() method returns the number of
milliseconds between midnight of January 1, 1970
and the specified date.
Syntax:-
getTime()
Sanjay Patel
The setTime() method sets a date and time by
adding or subtracting a specified number of
milliseconds to/from midnight January 1, 1970.
Syntax:-
setTime()
Sanjay Patel
The getHours() method returns the hour (from 0 to
23) of the specified date and time.
Syntax:-
The output of the code above will be:
1
getHours()
Sanjay Patel
The getHours() method returns the hour (from 0 to
23) of the specified date and time.
Syntax:-
The output of the code above will be:
Fri Nov 23 2012 15:35:01 GMT+0530
setHours()
Sanjay Patel
An array literal is written using square brackets with array elements separated
using by commas(,)..
var array_name=[element0, element2…..elementn];
Examples
var number=[1,2,3,4];
var alpha=[„a‟,‟b‟,‟c‟,‟d‟,‟e‟];
var colors=[“red”,”green”,”blue”];
How to access an element?
Same as other language
Name_of_an_array[index/subscript]
Example
number[0],number[2]
colors[0]
Array
Sanjay Patel
The following code creates an Array called cars:
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
It can also be declared as:
var cars=new Array("Saab","Volvo","BMW");
And even as:
var cars=["Saab","Volvo","BMW"];
Array
Sanjay Patel
Heterogeneous Array
Sanjay Patel
Array Example
Sanjay Patel
Output
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
Array concat
Sanjay Patel
Output
Sanjay Patel
The push() method adds new items to the end of
an array, and returns the new length.
Note: The new item(s) will be added at the end of
the array.
Note: This method changes the length of the array.
Array Push
Sanjay Patel
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits. Push("Kiwi“)
Banana,Orange,
Apple,Mango,Kiwi
The pop() method removes the last element of an
array, and returns that element.
Note: This method changes the length of an array.
Array Pop
Sanjay Patel
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
Banana,Orange,Apple
Array Join
Sanjay Patel
Output
Sanjay Patel
The shift() method removes the first item of an
array, and returns that item.
Note: This method changes the length of an array!
Tip: To remove the last item of an array, use the
pop() method.
Array Shift
Sanjay Patel
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits. Shift()
Orange, Apple,Mango
The unshift() method adds new items to the
beginning of an array, and returns the new length.
Note: This method changes the length of an array.
Tip: To add new items at the end of an array, use
the push() method
Array Unshift
Sanjay Patel
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon","Pineapple");
Lemon,Pineapple,Banana,
Orange,Apple,Mango
The slice() method returns the selected elements in
an array, as a new array object.
The slice() method selects the elements starting at
the given start argument, and ends at, but does not
include, the given end argument.
Syntax:- array.slice(start, end)
Slice()
Sanjay Patel
var fruits = ["Banana", "Orange", "Lemon",
"Apple", "Mango"];
var citrus = fruits. slice(1,3);
Orange,Lemon
Syntax:- array.slice(start, end)
Syntax
Sanjay Patel
Parameter Description
start Required. An integer that specifies where to start the
selection (The first element has an index of 0). Use
negative numbers to select from the end of an array
end Optional. An integer that specifies where to end the
selection. If omitted, all elements from the start position
and to the end of the array will be selected. Use
negative numbers to select from the end of an array
Example
Sanjay Patel
Output
Sanjay Patel
The splice() method adds/removes items to/from an
array, and returns the removed item(s).
Syntax:- array.splice(index,howmany,item1,.....,itemX)
splice()
Sanjay Patel
Parameter Description
index Required. An integer that specifies at what position
to add/remove items, Use negative values to
specify the position from the end of the array
howmany Required. The number of items to be removed. If
set to 0, no items will be removed
item1, ..., itemX Optional. The new item(s) to be added to the
array
Example
Sanjay Patel
var fruits = ["Banana", "Orange",
"Apple", "Mango"];
fruits.splice(2,0,"Lemon","Kiwi");
Banana,Orange,Lemon
,Kiwi,Apple,Mango
var fruits = ["Banana", "Orange",
"Apple", "Mango"];
fruits.splice(2,2,"Lemon","Kiwi");
Banana,Orange,Lemon,
Kiwi
var fruits = ["Banana", "Orange",
"Apple", "Mango"];
fruits.splice(2,1,"Lemon","Kiwi");
Banana,Orange,Lemon,
Kiwi,Mango
Date
String
Math
Built in Objects
Sanjay Patel
String Complete Example
Sanjay Patel
Output
Sanjay Patel
Date constructor
Sanjay Patel
Constructor Description
Date() This creates a Date object with the
current date and time of the browser‟s
PC
Date(“Month dd, yyyy hh:mm:ss”) This creates a Date object, with the
date specified by a date string in the
format “Month dd, yyyy hh:mm:ss”
Date(“Month dd, yyyy”) This creates a Date object, with the
date specified by a date string in the
format “Month dd, yyyy”
Date(yy, mm, dd hh, mm, ss) This creates a Date object with the
specified date and time
Date(yy, mm, dd) This creates a Date object with the
specified date
Full Date Example Demo
Sanjay Patel
Output
Sanjay Patel
abs()
ceil()
random()
pow()
floor()
sqrt()
Mathematical Functions
Sanjay Patel
Math() Object Example
Sanjay Patel
Output
Sanjay Patel
eval()
parseInt()
parseFloat()
isFinite()
Built in Function
Sanjay Patel
The eval() function evaluates or executes an argument.
If the argument is an expression, eval() evaluates the
expression. If the argument is one or more JavaScript
statements, eval() executes the statements.
Syntax
The eval() function is supported in all major browsers.
eval()
Sanjay Patel
The output of the code above will be:
200
4
27
Example
Sanjay Patel
parseInt()
Sanjay Patel
The parseInt() function parses a string and returns
an integer.
Syntax:-
The radix parameter is used to specify which numeral
system to be used, for example, a radix of 16
(hexadecimal) indicates that the number in the string
should be parsed from a hexadecimal number to a
decimal number
If the radix parameter is omitted, JavaScript assumes
the following:
If the string begins with "0x", the radix is 16
(hexadecimal)
If the string begins with "0", the radix is 8 (octal). This
feature is deprecated
If the string begins with any other value, the radix is
10 (decimal)
parseInt()
Sanjay Patel
Only the first number in the string is returned!
Leading and trailing spaces are allowed.
If the first character cannot be converted to a
number, parseInt() returns NaN.
parseInt()
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
parseFloat()
Sanjay Patel
The parseFloat() function parses a string and returns
a floating point number.
This function determines if the first character in the
specified string is a number. If it is, it parses the string
until it reaches the end of the number, and returns the
number as a number, not as a string.
Only the first number in the string is returned!
Leading and trailing spaces are allowed.
If the first character cannot be converted to a
number, parseFloat() returns NaN.
Cont‟d..
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
The isFinite() function determines whether a number
is a finite, legal number.
Syntax:-
This function returns false if the value is +infinity, -
infinity, or NaN.
isFinite()
Sanjay Patel
Example
Sanjay Patel
Output
Sanjay Patel
A function is a block of code that will be executed
when "someone" calls it:
A function is written as a code block (inside curly { }
braces), preceded by the function keyword:
User-defined Functions
Sanjay Patel
Cont‟d..
Sanjay Patel
Function Example
Sanjay Patel
Factorial with Function
Sanjay Patel
JavaScript has three kind of popup boxes.
Alert box.
Confirm box.
Prompt box.
JavaScript Pop boxes
Sanjay Patel
An alert box is often used if you want to make sure
information comes through to the user.
When an alert box pops up, the user will have to
click "OK" to proceed.
Syntax:-
window.alert("sometext");
Alert box
Sanjay Patel
Syntax
Sanjay Patel
There are many ways to add a handler to an
event. The straightforward way is to specify it in
the tag as follows
<input type=“button” value=“clickMe”
onClick=“alert(„You clicked Me‟);”
event Event Handler
<html><head> <script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
</head><body>
<input type="button" onclick="myFunction()" value="Show alert box“>
</body></html>
Example
Sanjay Patel
Output
Sanjay Patel
A confirm box is often used if you want the user to
verify or accept something.
When a confirm box pops up, the user will have to
click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the
user clicks "Cancel", the box returns false.
Syntax:-
window.confirm("sometext");
Confirm box
Sanjay Patel
Sanjay Patel
<html><body>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var r=confirm("Press a button!");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
document.getElementById("demo").innerHTML=x;
}
</script></body></html>
Output
Sanjay Patel
A prompt box is often used if you want the user to
input a value before entering a page.
When a prompt box pops up, the user will have to
click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input
value. If the user clicks "Cancel" the box returns null.
Syntax:-
window.prompt("sometext","defaultvalue");
Prompt box.
Sanjay Patel
Sanjay Patel
<html><body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var name=prompt("Please enter your name","Harry Potter");
if (name!=null)
{
x="Hello " + name + "! How are you today?";
document.getElementById("demo").innerHTML=x;
}
}
</script></body></html>
Output
Sanjay Patel
The getElementById() method accesses the first
element with the specified id.
This is the most powerful and the most complex
method (but don't worry, it's really easy!).
getElementById()
Sanjay Patel
Syntax:- document.getElementById("id")
Where id is required.
Everything on a web page resides in a box. A
paragraph (<P>) is a box.
When you mark something as bold you create a little
box around that text that will contain bold text.
You can give each and every box in HTML a unique
identifier (an ID), and Javascript can find boxes you
have labeled and let you manipulate them.
Well enough , check out the code!
Syntax
Sanjay Patel
<html><head></head>
<body>
<div id='feedback'></div>
<script type='text/javascript'>
document.getElementById('feedback').innerHTML=
'Hello World!';
</script>
</body></html> Output:- Hello World!
Code
Sanjay Patel
Here we defined a division <div> and named it "feedback".
That HTML has a name now, it is unique and that means we can
use JavaScript to find that block, and modify it.
We do exactly this in the script below the division! The left part
of the statement says on this web page (document) find a
block we've named "feedback" ( getElementById('feedback') ),
and change its HTML (innerHTML) to be 'Hello World!'.
We can change the contents of 'feedback' at any time, even
after the page has finished loading (which document.writeln
can't do), and without annoying the user with a bunch of pop-
up alert boxes (which alert can't do!).
Description
Sanjay Patel
innerHTML and getelementById
Sanjay Patel
Output
Sanjay Patel
Can you find out the Problem?
Sanjay Patel
Output
Sanjay Patel
Solution is:-getElementsByTagName() Method
Sanjay Patel
Output
Sanjay Patel
Input, of course, is a little more complicated. For
now we'll just reduce it to a bare click of the mouse.
If everything in HTML is a box and every box can
be given a name, then every box can be given an
event as well and one of those events we can look
for is "onClick".
Lets revisit our last example...
Input (One Click To Rule Them All)
Sanjay Patel
<html><head></head>
<body>
<div id='feedback' onClick='goodbye()'>Users without Javascript
see this.</div>
<script type='text/javascript„>
document.getElementById('feedback').innerHTML='Hello World!„;
function goodbye()
{
document.getElementById('feedback').innerHTML='Goodbye World!';
}
</script></body></html>
Mouse click example
Sanjay Patel
Output
Sanjay Patel
first we added an "onClick" event to our feedback
division which tells it to execute a function called
goodbye() when the user clicks on the division.
A function is nothing more than a named block of
code.
In this example goodbye does the exact same thing
as our first hello world example, it's just named and
inserts 'Goodbye World!' instead of 'Hello World!'.
Two Concept has been done
Sanjay Patel
Second new concept in this example is that we provided
some text for people without Javascript to see.
As the page loads it will place "Users without Javascript will
see this." in the division. If the browser has Javascript, and
it's enabled then that text will be immediately overwritten
by the first line in the script which looks up the division and
inserts "Hello World!", overwriting our initial message.
This happens so fast that the process is invisible to the user,
they see only the result, not the process.
The goodbye() function is not executed until it's explicitly
called and that only happens when the user clicks on the
division.
Cont‟d..
Sanjay Patel
Clicks are powerful and easy and you can add an
onClick event to pretty much any HTML element,
But sometimes you need to be able to ask for input
from the user and process it.
For that you'll need a basic form element and a
button…
Input (User Input)
Sanjay Patel
JavaScript is very good at processing user input in
the web browser
HTML <form> elements receive input
Forms and form elements have unique names
Each unique element can be identified
Uses JavaScript Document Object Model (DOM)
HTML Forms and JavaScript
Sanjay Patel
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
Naming Form Elements in HTML
Sanjay Patel
Forms and JavaScript
Sanjay Patel
document.formname.elementname.value
Thus:
document.addressform.yourname.value
document.addressform.phone.value
document.addressform.email.value
Using Form Data
Sanjay Patel
Personalising an alert box
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' +
document.alertform.yourname.value);">
</form>
<html><head></head> <body>
<input id='userInput' size=60>
<button onClick='userSubmit()'>Submit</button><BR>
<div id='result'></div>
<script type='text/javascript„>
function userSubmit()
{
var UI=document.getElementById('userInput').value;
document.getElementById('result').innerHTML='You typed: '+UI;
}
</script></script></body></html>
Example
Sanjay Patel
Output
Sanjay Patel
Here we create an input field and give it a name of
userInput.
Then we create a HTML button with an onClick event
that will call the function userSubmit().
These are all standard HTML form elements but
they're not bound by a <form> tag since we're not
going to be submitting this information to a server.
Instead, when the user clicks the submit button, the
onClick event will call the userSubmit() function
Explanation
Sanjay Patel
we create a variable called UI which looks up the
input field userInput.
This lookup is exactly the same as when we looked up
our feedback division in the previous example.
Since the input field has data, we ask for its value
and place that value in our UI variable.
The next line looks up the result division and puts our
output there.
In this case the output will be "You Typed:
" followed by whatever the user had typed into the
input field.
Cont‟d..
Sanjay Patel
<html><head></head><body>
<input id='userInput' onKeyUp="userSubmit()" size=60><BR>
<div id='result'></div>
<script type='text/javascript„>
function userSubmit()
{
var UI=document.getElementById('userInput').value;
document.getElementById('result').innerHTML='You typed: '+UI;
}
</script></body></html>
onkeyup() event (Without Button)
Sanjay Patel
Output
Sanjay Patel
Password Validation Criteria
Sanjay Patel
Password Validation Example
Sanjay Patel
<script type="text/javascript“>
function confirmPass()
{
var sa = document.getElementById("pass").value;
var confPass = document.getElementById("c_pass").value;
if(sa==null)
{ alert("please enter");
pass.focus();
return false; }
else if(sa!= confPass)
{ alert("re-enetr!");
pass.focus();
pass.select();
return false; }
else {
alert("enjoy");
return true; } }
Email Validation
Sanjay Patel
Expression Description
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[A-z] Find any character from uppercase A to lowercase z
[adgk] Find any character in the given set
(red|blue|green) Find any of the alternatives specified
Regular Expression
Sanjay Patel
Brackets are used to find a range of characters.
Metacharacters are characters with a special meaning.
Regular Expression
Sanjay Patel
Metacharacter Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
The purpose of using JavaScript is to add interactivity in
web pages. i.e. we need to respond to user actions.
When users performs some tasks on a web page are
called events.
For example, when user click on a button on a web
page, a click event occurs. The button is called the
source of the event.
Other events such as, hyperlink( mouse over event),
submitting a form(submit event), a keystroke (key press
event)
Event
Sanjay Patel
JavaScript identifies an event and takes an action by
executing piece of code.
The procedure of taking action is called event handling
The specific JavaScript code that take the action is
called event handler.
An event handler may be any valid JavaScript
statements.
In JavaScript, the handler of an event is usually
provided as a function.
Event Handlers
Sanjay Patel
Window object Method
Sanjay Patel
Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height`
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
setInterval() Calls a function or evaluates an expression at specified intervals (in milliseconds)
setTimeout() Calls a function or evaluates an expression after a specified number of milliseconds
Example
Sanjay Patel
Output
Sanjay Patel
Sanjay Patel
Sanjay Patel
Example
Sanjay Patel
Sanjay Patel
Sanjay Patel
Prompt Box Demo
Output
Sanjay Patel
As you can tell from the input examples, Javascript
is an event driven language which means your
scripts react to events you set up. Your code isn't
running all the time,
it simply waits until an event starts something up!
Going into all the JavaScript events is beyond the
scope of this document
but here's a short-list of common events to get you
started.
Java Script is an Event Driven Language
Sanjay Patel
Sanjay Patel
The JavaScript window object has a property location
(access by window.location or location), which
encapsulates the current URL that is displayed in the
visitor‟s browser.
This object has several useful properties and methods
that may be used to inspect or changed different
fields of a URL or even change the entire URL.
Location Object
Sanjay Patel
Example
Sanjay Patel
Another Location Object Example
Sanjay Patel
The JavaScript window object has another important
property history (accessed as window.history or
history ), which stores information about URLs already
visited from the browser‟s window.
History Object
Sanjay Patel
Property Description
length Returns the number of URLs in the history list
Method Description
back() Loads the previous URL in the history list
forward() Loads the next URL in the history list
go() Loads a specific URL from the history list
Example
Sanjay Patel
The HTML DOM defines a standard way for
accessing and manipulating HTML documents.
The DOM presents an HTML document as a tree-
structure.
In Simple words, With the HTML DOM, JavaScript
can access all the elements of an HTML document.
When a web page is loaded, the browser creates a
Document Object Model of the page.
The HTML DOM model is constructed as a tree of
Objects:
HTML DOM
Sanjay Patel
Document object model is a set of platform
independent and language-neutral application
programming interface(API) which describes how to
access and manipulate the information stored in
XML,XHTML and javaScript document
DOM is a platform- and language-neutral interface
that allow programs and scripts to dynamically
access and manipulate the content, structure and
style of documents.
What is DOM?
Sanjay Patel
HTML DOM Tree
Sanjay Patel
According to the DOM, everything in an HTMLdocument is a node.
The DOM says:
The entire document is a document node
Every HTML element is an element node
The text in the HTML elements are text nodes
Every HTML attribute is an attribute node
Comments are comment nodes
DOM Node
Sanjay Patel
The root node in the HTML
above is <html>. All other
nodes in the document are
contained within <html>.
The <html> node has two
child nodes; <head> and
<body>.
The <head> node holds a
<title> node. The <body>
node holds a <h1> and
<p> node.
Example
Sanjay Patel
In the DOM, HTML documents consist of a set of node
objects. The nodes can be accessed with JavaScript or
other programming languages
Properties are often referred to as something that is
(i.e. the name of a node).
Methods are often referred to as something that is
done (i.e. remove a node).
Programming Interface
Sanjay Patel
x.innerHTML - the text value of x
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x
HTML DOM Properties
Sanjay Patel
x.getElementById(id) - get the element with a
specified id
x.getElementsByTagName(name) - get all elements
with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x
HTML DOM Methods
Sanjay Patel
The easiest way to get or modify the content of an
element is by using the innerHTML property.
innerHTML is not a part of the W3C DOM
specification. However, it is supported by all major
browsers.
The innerHTML property is useful for returning or
replacing the content of HTML elements (including
<html> and <body>), it can also be used to view
the source of a page that has been dynamically
modified.
The innerHTML Property
Sanjay Patel
Example
Sanjay Patel
We can access a node in three ways:
By using the getElementById() method
By using the getElementsByTagName() method
By navigating the node tree, using the node
relationships
Accessing Nodes
Sanjay Patel
<html><body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").
innerHTML="New text!";
</script>
<p>The paragraph above was
changed by a script.</p>
</body></html>
JavaScript HTML DOM - Changing HTML
Sanjay Patel
New text!
The paragraph
above was
changed by a
script
<html><body>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
document.getElementById("p2").style.fontFamily="Arial";
document.getElementById("p2").style.fontSize="larger";
</script>
<p>The paragraph above was changed by a script.</p>
</body></html>
JavaScript HTML DOM - Changing CSS
Sanjay Patel
Hello World!
Hello World!
The paragraph above was changed by a script.
Cont‟d..
Sanjay Patel
DHTML is the combination of 3 browser technologies to render a dynamic browser experience
HTML for content
Cascading Style Sheets for general presentation
Javascript to enable dynamic presentation
Generally, DHTML refers to applications that allow a Web page to change dynamically without requiring information to be passed to/from a web server.
More specifically, DHTML refers to the interaction of HTML, CSS and Scripting language (JavaScript).
DHTML = HTML + CSS + JavaScript + DOM
DHTML
Sanjay Patel
Affect the DOM through
Sanjay Patel
Browser
DOM
HTML
(content) Cascading Style
Sheets (general
presentation)
Javascript (and
other scripting
languages) for
most dynamic
effects
With Dynamic HTML the emphasis is on making the browser provide a richer viewing experience through effects like
Animation
Filters
Transitions
This is done by applying properties and methods of the Browser‟s Document Object Model (DOM)
This is usually done through Javascript, but it can also be done by any scripting language supported by the browser, such as VB-Script
Why comes DHTML?
Sanjay Patel
To make Web pages interactive.
HTML pages have static nature.
DHTML provides us with enhanced creative control
so we can manipulate any page element at any
time.
It is the easiest way to make Web pages interactive.
It doesn‟t increase server workload and require
special software to support.
In simple Words.
Sanjay Patel
HTML DHTML
HTML is used to create static web
pages
DHTML is used to create Dynamic web
pages
The HTML consists of simple HTML tags DHTML is made up of HTML tags +
CSS + Java Script
The HTML does not allow to alter the
text and graphics on the web page
unless web page get changed
DHTML , you can alter the text and
graphics of the web page and for
that matter you need not have to
change the entire web page.
Creation of HTML web pages is
simplest but less interactive
Creation of DHTML web pages is
complex but more interactive
Difference Between HTML and DHTML
Sanjay Patel
HTML DOM and JavaScript can change the inner
content and attributes of HTML elements.
The following example changes the background
color of the <body> element:
Change an HTML Element
Sanjay Patel
Example
Sanjay Patel