Chapter 3 JS

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 78

Chapter 3:

JavaScript (JS)
Outline
 Introduction
• Task Performed by Client side Scripts
• Pros & Cons of Client side Scripts
• Client side Scripts V/S Server side Scripts
 Variables
 Functions
 Conditions & Loops
 Pop up boxes
 JavaScript Objects
 DOM
 DHTML

2
Unit
Unit –– 5:
5: JS
JS 22 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Introduction (refer chapter 1:)

Scripting Language:-
 is a type of languages that is designed to integrate and communicate
with other programming languages.
 helps to control one or more multiple applications without the need
of compilation.
 used to give guidance to another program or to control another
program.
 used in conjunction with other languages, either programming
language or markup language.
 eg. PHP which is a scripting language is mostly used in conjunction
with HTML.
 example:- JavaScript, VB script,Php.
 All scripting languages are programming languages, but not all
programming languages are scripting languages.
client side scripting language vs Server side scripting
 The program written using a scripting language is converted into
machine code by an interpreter.
 Scripting languages can be divided into two
1. client side scripting languages:- generate a code that execute in web
browsers.
eg JavaScript
2. server side scripting language :- generate code that executes on a
web server.
e.g. PHP,Perl,python

4
JavaScript
   1. HTML to define the content and structure of web pages.
  2. CSS to specify the layout of web pages.
3. JavaScript to program the behavior of web pages.
• For a Web page, HTML supplies document content and structure
while CSS provides presentation styling
• In addition, client-side scripts can control browser actions associated
with a Web page.
• Client-side scripts are almost written in the Javascript language to
control browser’s actions.
• Client-side scripting can make Web pages more dynamic and more
responsive
• JavaScript is client-side scripting language, which means it runs on the
user’s machine and not on the server,

5
Unit
Unit –– 5:
5: JS
JS 55 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Tasks performed by client-side scripts
 Checking correctness of user input
 Monitoring user events and specifying reactions
 Replacing and updating parts of a page
 Changing the style and position of displayed elements
dynamically
 Modifying a page in response to events
 Getting browser information
 Making the Web page different depending on the browser and
browser features
 Generating HTML code for parts of the page

6
Unit
Unit –– 5:
5: JS
JS 66 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Pros & Cons of Client Side Scripting
Pros
– Allow for more interactivity by immediately responding to users’
actions.
– Execute quickly because they do not require a trip to the server.
– The web browser uses its own resources, and eases the burden
on the server.
– It saves network bandwidth.
Cons
– Code is loaded in the browser so it will be visible to the client.
– Code is modifiable.
– Local files and databases cannot be accessed.
– User is able to disable client side scripting

7
Unit
Unit –– 5:
5: JS
JS 77 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Client V/S Server Side Scripting
Server Side Scripting Client Side Scripting
Server side scripting is used to create Client side scripting is used when the users
dynamic pages based on a number of browser already has all the code and the
conditions when the users browser makes a page is altered on the basis of the users
request to the server. input.
The Web Server executes the server side The Web Browser executes the client side
scripting that produces the page to be sent scripting that resides at the user’s computer.
to the browser.
Server side scripting is used to connect to Client side scripting cannot be used to
the databases and files that reside on the connect to the databases and files on the
web server. web server.

8
Unit
Unit –– 5:
5: JS
JS 88 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Client V/S Server Side Scripting (Cont)
Server Side Scripting Client Side Scripting
Server resources can be accessed by the Browser resources can be accessed by the
server side scripting. client side scripting.
Server side scripting can’t be blocked by the Client side scripting is possible to be blocked
user. 0 by the user.
Examples of Server side scripting languages : Examples of Client side scripting languages :
PHP, JSP,  ASP, ASP.Net, Ruby, Perl and many Javascript, VB script, etc.
more.

9
Unit
Unit –– 5:
5: JS
JS 99 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
What JavaScript can do?
1. JavaScript Can Change HTML Content
 One of many HTML methods is getElementById().
 This example uses the method to "find" an HTML element (with
id="demo"), and changes the element content (innerHTML) to
"Hello JavaScript":
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'">
Click Me!</button>
</body>
 To access an HTML element, JavaScript can use
the document.getElementById(id) method.
 The id attribute defines the HTML element.
 The innerHTML property defines the HTML content:
What JavaScript can do?
2. JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML
attribute:
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<script>
function myFunction() {
var x = document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
</script>
</body>
3. JavaScript Can Validate Data
 JavaScript is often used to validate input:
4. JavaScript Can Change HTML Attributes
<script> tag & Where to Place
 JavaScript can be placed in the <body> and the <head> sections
of an HTML page or placed as external.
 The <script> tag is used to define a client-side script
(JavaScript).
 The <script> element either contains scripting statements, or it
points to an external script file through the src attribute.
 Example : JavaScript in <body>
Code
<html>
<head>
<title>HTML script Tag</title>
</head>
<body>
<script type="text/javascript">
// Java Script Code Here
</script>
</body>
</html> 12
Unit
Unit –– 5:
5: JS
JS 12
12 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
JavaScript in <head>
 In this example, a JavaScript function is placed in the
<head> section of an HTML page.
 The function is invoked (called) when a button is clicked:
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML =
"Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try
it</button>
External JavaScript
 Scripts can also be placed in external files.
 External scripts are practical when the same code is used in many
different web pages.
 JavaScript files have the file extension .js.
 To use an external script, put the name of the script file in the src
(source) attribute of the <script> tag:
Syntax: <script src=“PathToJS”>
</script>
Code
<html>
<head>
<title>HTML script Tag</title>
</head>
<body>
<script src=“PathToJS”>
</script>
</body>
</html>
External JavaScript (Example)
message.js
function myAlert(msg) {
if(confirm("Are you sure you want to display the message????")) {
alert(msg);
}
else {
alert("Message not Displayed as User Cancled Operation");
}
}

myHtml.html
<html>
<head>
<script src=“message.js”></script>
</head>
<body>
<script> myAlert(“Hello World”); </script>
</body>
</html>
15
Unit
Unit –– 5:
5: JS
JS 15
15 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
JavaScript Output /JavaScript Display Possibilities

 JavaScript can "display" data in different ways:


 Writing into an alert box, using window.alert().
 Writing into the HTML output using document.write().
 Writing into an HTML element, using innerHTML.
 Writing into the browser console, using console.log().

16
window.alert() Using document.write()
alert.html
write.html

 You can use an alert box to  For testing purposes, it is convenient to


display data: use document.write():
 Example
 Example
<body> <html>
<h1>My First Web Page</h1> <body>
<p>My first paragraph.</p> <h1>My First Web Page</h1>
<script> <p>My first paragraph.</p>
window.alert(5 + 6);
<script>
</script> document.write(5 + 6);
</body> </script>

</body>
</html>

17
Using innerHTML

 To access an HTML element, JavaScript can use


the document.getElementById(id) method.
 The id attribute defines the HTML element.
 The innerHTML property defines the HTML content
innerHTML.html

<body>
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body

18
JavaScript Statements
 JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
JavaScript Values
 The JavaScript syntax defines two types of values: Fixed values
and variable values.
 Fixed values are called literals (e.g 10.50 , 1001).
 Variable values are called variables.(e.g )
JavaScript Variables
• In a programming language, variables are used to store data values.
• JavaScript uses the var keyword to declare variables.
• An equal sign is used to assign values to variables.
• In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;
x = 6;
• A variable can contain several types of value:
–Number : a numeric value e.g. 156, 100, 1.2
–String : character wrapped in quotes e.g. “hi”
–Boolean : a value of true or false
–Null : an empty variable/represents null i.e. no value at all
–Undefined: represents undefined value
–Function : a function name
–Object : an object
Example:-
–var length = 16;                               // Number
var lastName = “bogale";                      // String
var cars = ["Saab", "Volvo", "BMW"];           // Array
var x = {firstName:“abebe", lastName:“kebede"};    // Object 20
Unit
Unit –– 5:
5: JS
JS 20
20 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
JavaScript Variables
 Undefined: In JavaScript, a variable without a value, has the
value undefined.
 Example
 var person;                  // Value is undefined,
 Any variable can be emptied, by setting the value to undefined.
 The type will also be undefined.
 Example
 person = undefined;          // Value is undefined,

 Q 1. What is the difference between null and undefined explain


with example??
 Q 2.what is global variable vs local variable with example

21
Unit
Unit –– 5:
5: JS
JS 21
21 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Naming JavaScript Variables
 There are some rules while declaring a JavaScript variable (also
known as identifiers).
 Name must start with a letter (a to z or A to Z), underscore( _ ),
or dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for example value1.
 JavaScript variables are case sensitive, for example x and X are
different variables.

 JavaScript is untyped language.
 This means that a JavaScript variable can hold a value of any data
type.
 Unlike many other languages, you don't have to tell JavaScript
during variable declaration what type of value the variable will
hold.
22
Unit
Unit –– 5:
5: JS
JS 22
22 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
JavaScript Operators

 JavaScript operators are symbols that are used to perform operations


on operands. For
 example: var sum=10+20;   Here, + is the arithmetic operator and = is
the assignment operator.
 There are following types of operators in JavaScript.
 Arithmetic Operators ( +,-,*,/,%,++,--)
 Comparison (Relational) Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Special Operators

23
JavaScript Comparison Operators

 The JavaScript comparison operator compares the two operands.


 The comparison operators are as follows:
Operator Description Example
== Is equal to 10==20 = false
=== Identical (equal and 10==20 = false
of same type)
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or 20>=10 = true
equal to
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false

24
JavaScript Logical Operators

The following operators are known as JavaScript logical operators.


Operator Description Example
&& Logical AND (10==20 &&
20==33) = false
|| Logical OR (10==20 ||
20==33) = false
! Logical Not !(10==20) = true

25
JavaScript Assignment Operators
The following operators are known as JavaScript assignment
operators.
Operator Description Example
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20;
Now a = 30
-= Subtract and assign var a=20; a-=10;
Now a = 10
*= Multiply and assign var a=10; a*=20;
Now a = 200
/= Divide and assign var a=10; a/=2;
Now a = 5
%= Modulus and assign var a=10; a%=2;
Now a = 0

26
Conditional statements
 Conditional statements are used to perform different actions
based on different conditions.
 Very often when you write code, you want to perform
different actions for different decisions.
 You can use conditional statements in your code to do this.
 In JavaScript we have the following conditional statements:
 Use if to specify a block of code to be executed, if a specified
condition is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition
is false
 Use switch to specify many alternative blocks of code to be
executed
Conditions
If condition switch
if (condition) { switch(expression)
    block of code to be executed {
if the condition is true case lbl1:
} // code to execute
break;
The else Statement case lbl2:
if (condition) { // code to execute
    block of code to be executed if the break;
condition is true
} else { }
    block of code to be executed if the
condition is false
}

28
Unit
Unit –– 5:
5: JS
JS 28
28 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Loops
 Loops can execute a block of code a number of times.

for loop while loop do while loop


Use when you know how Loops through block of code Execute block at least once
many repetitions you want while condition is true then repeat while condition
to do is true

syntax syntax syntax


for(initialize ; condition ; while(condition) { … } do{ … } while (condition);
increment) { … }

example example example


for(x=0;x<10;x++) { while (x<10) { do{
// Code Here //Code Here // Code Here
} } } while (x<10)
29
Unit
Unit –– 5:
5: JS
JS 29
29 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Arrays
 The Array object lets you store multiple values in a single variable.
 It stores a fixed-size sequential collection of elements of the same type.
 An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type
 There are 3 ways to construct array in JavaScript
 By array literal
 By creating instance of Array directly (using new keyword)
 By using an Array constructor (using new keyword)
1) JavaScript array literal
 The syntax of creating array using array literal is given below:
 var arrayname=[value1,value2.....valueN];  
 As you can see, values are contained inside [ ] and separated by , (comma).
e.g var student=[“almaz",“abebe",“kebede"]; 

30
Unit
Unit –– 5:
5: JS
JS 30
30 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
2) JavaScript Array directly (new keyword)
 The syntax of creating array directly is given below:
var arrayname=new Array();  
 Here, new keyword is used to create instance of array.
 Let’s see the example of creating array directly.
<script>  
var i;  
var emp = new Array();  
emp[0] = “almaz";  
emp[1] = “abebe ";  
emp[2] = “kebede "; 
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in
constructor so that we don't have to provide value explicitely.
The example of creating object by array constructor is given below.
<script>  var emp=new Array(“almaz",“abebe",“kebede"); </script>
31
Array Methods
 .
Method Description
concat() Returns a new array comprised of this array joined with other array(s) and/or value(s).
every() Returns true if every element in this array satisfies the provided testing function.
filter() Creates a new array with all of the elements of this array for which the provided filtering function
returns true.

forEach() Calls a function for each element in the array.


indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is
found.

join() Joins all elements of an array into a string.


pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of the array.
reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a
single value.

reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the
first.
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
toSource() Represents the source code of an object
splice() Adds and/or removes elements from an array.
toString() Returns a string representing the array and its elements.
32
JS Functions
 A JavaScript function is a block of code designed to perform a
particular task.
 A JavaScript function is executed when "something" invokes it.
 A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ().
 The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly
brackets.
• Example :

Code
function myFunction(p1, p2) {
return p1 * p2;
}

33
Unit
Unit –– 5:
5: JS
JS 33
33 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
 Function names can contain letters, digits, underscores, and dollar
signs (same rules as variables).
 Syntax:
function name(parameter1, parameter2, parameter3) {
    code to be executed
}
 Function parameters are the names listed in the function definition.
 Function arguments are the real values received by the function when
it is invoked.

34
Functions (Cont.)
 When JavaScript reaches a return statement, the function will
stop executing.
 If the function was invoked from a statement, JavaScript will
"return" to execute the code after the invoking statement.
 The code inside the function will execute when "something"
invokes (calls) the function:
– When an event occurs (when a user clicks a button)
– When it is invoked (called) from JavaScript code
– Automatically (self invoked)

35
Unit
Unit –– 5:
5: JS
JS 35
35 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
example
<body>
<p>This example calls a function which performs a calculation, and returns the
result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {      // Function returns the product of a and b
}
document.getElementById("demo").innerHTML = myFunction(4, 3); // Function is
called, return value will end up in x
</script>
Output:
</body>
This example calls a function which performs a calculation, and returns the result:
12

36
Pop up Boxes
 Popup boxes can be used to raise an alert, or to get confirmation on
any input or to have a kind of input from the users.
 JavaScript supports three types of popup boxes.
– Alert box
– Confirm box
– Prompt box

37
Unit
Unit –– 5:
5: JS
JS 37
37 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Alert Box
 An alert box is 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.
 It can be used to display the result of validation.

Code
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<script>
alert("Hello World");
</script>
</body>
</html>
38
Unit
Unit –– 5:
5: JS
JS 38
38 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Confirm Box
• A confirm box is used if you want the user to 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.
• Example Code
:
<script>
var a = confirm(“Are you sure??");
if(a==true) {
alert(“User Accepted”);
}
else {
alert(“User Cancled”);
}
</script>
39
Unit
Unit –– 5:
5: JS
JS 39
39 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Prompt Box
• A prompt box is used if you want the user to input a value.
• When a prompt box pops up, user have to click either "OK" or
"Cancel" to proceed, If the user clicks "OK" the box returns the
input value, If the user clicks "Cancel" the box returns null.

Code
<script>
var a = prompt(“Enter Name");
alert(“User Entered ” + a);
</script>

40
Unit
Unit –– 5:
5: JS
JS 40
40 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
JavaScript Objects
• An object is just a special kind of data, with properties
and methods.
• Accessing Object Properties
– Properties are the values associated with an object.
– The syntax for accessing the property of an object is below
objectName.propertyName
– This example uses the length property of the Javascript’s
inbuilt object(String) to find the length of a string:
var message="Hello World!";
var x=message.length;

41
Unit
Unit –– 5:
5: JS
JS 41
41 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
JavaScript Objects (Cont.)
• Accessing Object Methods
– Methods are the actions that can be performed on
objects.
– You can call a method with the following syntax.
objectName.methodName()
– This example uses the toUpperCase method of the
String object to convert string to upper case:
var message="Hello World!";
var x=message.toUpperCase();

42
Unit
Unit –– 5:
5: JS
JS 42
42 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
User Defined Objects
• JavaScript allows you to create your own objects.
• The first step is to use the new operator.
var myObj= new Object();
• This creates an empty object.
• This can then be used to start a new object that
you can then give new properties and methods.
• In object- oriented programming such a new
object is usually given a constructor to initialize
values when it is first created.
43
Unit
Unit –– 5:
5: JS
JS 43
43 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
User - Defined Objects (Cont.)
• However, it is also possible to assign values
example
when it is made with literal values.
<script>
person={
firstname: "Darshan",
lastname: "College",
age: 50,
eyecolor: "blue"
}
alert(person.firstname + " is " + person.age + " years old.");
</script>

44
Unit
Unit –– 5:
5: JS
JS 44
44 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
User - Defined Objects (Cont.)
• A constructor is pre defined method that will
initialize your object.
• To do this in JavaScript a function is used that
is invoked through the new operator.
example
<script>
• function
Any properties insideage){
person(firstname, lastname, the newly created object
this.firstname = firstname;
arethis.lastname
assigned using this keyword, referring to
= lastname;
this. changeFirstName = function (name){ this.firstname = name };
}the current object being created.
var person1=new person("Narendra","Modi",50);
person1.changeFirstName(“NAMO”);
alert(person1.firstname + “ ”+ person1.lastname);
</script>
45
Unit
Unit –– 5:
5: JS
JS 45
45 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Handling Events and Exception Handling
 Event handlers are attributes that force an element to "listen" for a
specific event to occur.
 Event handlers all begin with the letters "on".
 JavaScript's interaction with HTML is handled through events that
occur when the user or the browser manipulates a page.
 Examples of an event
 When the page loads, it is called an event.
 When the user clicks a button, that click too is an event.
 Other examples include events like pressing any key, closing a
window, resizing a window, etc
 Events: actions taken by the Web page visitor
clicking (onclick),
◦ placing the mouse on an element (onmouseover),
◦ removing the mouse from an element
(onmouseout),
◦ loading the page (onload),
◦ unloading the page (onunload), etc. 46
onclick Event Type
 This is the most frequently used event type which occurs when a
user clicks the left button of his mouse.
 You can put your validation, warning etc., against this event type.
 Example: Try the following example
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say
Hello" />
</form>
47
</body>
onsubmit Event type
 onsubmit is an event that occurs when you try to submit a form. You can
put your form validation against this event type.
 Example: The following example shows how to use onsubmit.
 Here we are calling a validate() function before submitting a form data to
the webserver. If validate() function returns true, the form will be
submitted, otherwise it will not submit the data.
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
48
</body>
Exception handling

Exceptions:
 Are events which may be considered exceptional or
unusual.
 Indication of problem during execution.
 An exception is a representation of an error condition or
a situation that is not the expected result of a program.
 avaScript Errors - Throw and Try to Catch
 The try statement lets you test a block of code for errors.
 The catch statement lets you handle the error.
 The throw statement lets you create custom errors.
 The finally statement lets you execute code, after try and
catch, regardless of the result

49
Syntax
try { The finally Statement
    Block of code to try The finally statement lets you execute
} code, after try and catch, regardless of the
catch(err) {
result:
    Block of code to handle errors
}
try {
    Block of code to try
}
catch(err) {
    Block of code to handle errors
}
finally {
    Block of code to be executed regardless
of the try / catch result

50
Document Object Model (DOM)
 The document object represents the whole html document.
 When html document is loaded in the browser, it becomes a document
object.
 The Document object has various properties that refer to other objects
which allow access to and modification of document content.
 The way a document content is accessed and modified is called
the Document Object Model, or DOM.
 It is the root element that represents the html document.
 The DOM is a platform and language neutral interface that will allow
programs and scripts to dynamically access and update the content,
structure and style of documents
 With JavaScript, we can restructure an entire HTML document by
adding, removing, changing, or reordering items on a page

51
Unit
Unit –– 5:
5: JS
JS 51
51 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Document Object Model (DOM)
 The Objects are organized in a hierarchy.
 This hierarchical structure applies to the organization of objects in a Web
document.
 Window object − Top of the hierarchy. It is the outmost element of the
object hierarchy
 window object represents the window or frame that displays the
document and is the global object in client side programming for
JavaScript.
 All the client side objects are connected to the window object .
 Document object − Each HTML document that gets loaded into a window
becomes a document object. The document contains the contents of the
page.
 Form object − Everything enclosed in the <form>...</form> tags sets the
form object.
 Form control elements − The form object contains all the elements
defined for that object such as text fields, buttons, radio buttons, and
checkboxes.
Unit
Unit –– 5:
5: JS
JS 52
52 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
52
& Technology
Technology
DOM (Cont)
• This window object represents the window or
frame that displays the document and is the
global object in client side programming for
JavaScript.
• All the client sidewindow
objects are connected to the
window object.

self, frames[] navigator location history document screen


parent,
window,
top

53
Unit
Unit –– 5:
5: JS
JS 53
53 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
54
Unit
Unit –– 5:
5: JS
JS 54
54 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
What is the HTML DOM?

 The HTML DOM is a standard object model and programming


interface for HTML.
 It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
 In other words: The HTML DOM is a standard for how to get,
change, add, or delete HTML elements.
 JavaScript HTML DOM - Changing HTML
 Changing HTML Content
 Changing the Value of an Attribute
 Changing HTML Style

55
JavaScript HTML DOM - Changing HTML
Changing HTML Content
 The easiest way to modify the content of an HTML element is by
using the innerHTML property.
 To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML = new HTML
 document is the root element that represents the html document.
This example changes the content of a <p> element:
Example
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body> 56
</html>
JavaScript HTML DOM - Changing HTML
Changing the Value of an Attribute
 To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute=new value
 This example changes the value of the src attribute of an <img>
element:
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>

57
JavaScript HTML DOM - Changing HTML
Changing HTML Style/Changing CSS
 To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
 The following example changes the style of a <p> element:
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>

58
 Document Object Properties
properties of document object that can be accessed and modified
by the document object

Property Description
anchors Returns a collection of all the anchors in the document
applets Returns a collection of all the applets in the document
body Returns the body element of the document
cookie Returns all name/value pairs of cookies in the document
Returns the domain name of the server that loaded the
domain document
forms Returns a collection of all the forms in the document
images Returns a collection of all the images in the document
links Returns a collection of all the links in the document (CSSs)
Returns the URL of the document that loaded the current
referrer document
title Sets or returns the title of the document
URL Returns the full URL of the document

Unit
Unit –– 5:
5: JS
JS 59
59 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Methods of document object
 We can access and change the contents of document by its
methods.
 DOM Document methods for finding HTML elements
Method Description

getElementById() returns the element having the


given id value.

getElementsByName() returns all the elements having


the given name value.

getElementsByTagName() returns all the elements having


the given tag name.

getElementsByClassName() returns all the elements having


the given class name.

60
getElementById()
 returns the element of specified id.
 Example :

<script type="text/javascript">  
function getcube(){  
var number=document.getElementById
("number").value;  
alert(number*number*number);  
}  
</script>  
<form>  
Enter No:<input type="text" id="numb
er" name="number"/><br/>  
<input type="button" value="cube" on
click="getcube()"/>  
</form> 

61
Unit
Unit –– 5:
5: JS
JS 61
61 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
getElementsByName()

• returns all the element of specified name.


• The syntax of the getElementsByName() method is given :
document.getElementsByName("name") 
• Example :
<script type="text/javascript">
function totalelements()
{
Var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total


Genders">
</form>

62
Unit
Unit –– 5:
5: JS
JS 62
62 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
getElementsByTagName()
 When we suppose to get the reference of the elements from HTML in
JavaScript using name of the tag specified in the HTML we can use
this method.
 It will return the array of elements with the provided tag name.
 Syntax: document.getElementsByTagName("name")  
 Example :
<h2>This is h2 tag</h2>  
<script type="text/javascript">   <h2>This is h2 tag</h2>  
functtotalh2=document.getElementsByTagNam <h3>This is h3 tag</h3>  
e("h2");   <h3>This is h3 tag</h3>  
alert("total h2 tags are: "+totalh2.length);   <h3>This is h3 tag</h3>  
}   <button onclick="counth2()">count h2<
function counth3(){   /button>  
var totalh3=document.getElementsByTagName <button onclick="counth3()">count h3<
("h3");   /button> 
alert("total h3 tags are: "+totalh3.length);   ion counth2(){  
}   var
</script>  
63
Unit  
Unit –– 5:
5: JS
JS 63
63 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Javascript - innerHTML
 The innerHTML property can be used to write the dynamic html on the html
document.
 It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.
   Example : example, we are dynamically writing the html form inside the div
name having the id mylocation.
 We are identifing this position by calling the document.getElementById()
method
<script type="text/javascript" >  
function showcommentform() {  
var data="Name:<input type='text' name='name'><br>Comment:<textarea ro
ws='5' cols='80'></textarea><br><input type='submit' value='comment'>";  
  
document.getElementById('mylocation').innerHTML=data;  
 }  
  </script>  
<form name="myForm">  
<input type="button" value="comment" onclick="showcommentform()">  
<div id="mylocation"></div>   64
Unit
Unit –– 5:
5: JS
JS</form>  64
64 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Validation
• Validation is the process of checking data against a standard or
requirement.
• Form validation normally used to occur at the server, after client
entered necessary data and then pressed the Submit button.
• If the data entered by a client was incorrect or was simply missing,
the server would have to send all the data back to the client and
request that the form be resubmitted with correct information.
• This was really a lengthy process which used to put a lot of burden
on the server.
• JavaScript provides a way to validate form's data on the client's
computer before sending it to the web server.

65
Unit
Unit –– 5:
5: JS
JS 65
65 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Validation (Cont.)
Form validation generally performs two functions.
1. Basic Validation
• Emptiness
• Confirm Password
• Length Validation etc……
2. Data Format Validation
Secondly, the data that is entered must be checked for
correct form and value.
• Email Validation
• Mobile Number Validation
• Enrollment Number Validation etc….

66
Unit
Unit –– 5:
5: JS
JS 66
66 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Validation using RegExp
• A regular expression is an object that describes a pattern of
characters.
• Regular expressions are used to perform pattern-matching and
"search-and-replace" functions on text.
• example:
var pattern = "^ [\\w]$"; // will allow only words in the string
var regex = new RegExp(pattern);
If(regex.test(testString)){
//Valid
} else {
//Invalid
}

67
Unit
Unit –– 5:
5: JS
JS 67
67 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RegExp (Cont.) (Metacharacters)
• To find word characters in the string we can use \w
– We can also use [a-z], [A-Z] or [a-zA-Z] for the same
• To find non-word characters in the string we can
use \W
• to find digit characters in the string we can use \d
– We can also use [0-9] for the same
• To find non-digit characters in the string we can
use \D
• We can use \n for new line and \t for tab

68
Unit
Unit –– 5:
5: JS
JS 68
68 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RegExp (Cont.) (Quantifiers)
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's

69
Unit
Unit –– 5:
5: JS
JS 69
69 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Email Validation Using RegExp
JavaScript
<script>
function checkMail()
{
var a = document.getElementById("myText").value;
var pattern ="^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$”;
var regex = new RegExp(pattern);
if(regex.test(a))
{
alert("Valid");
}
else
{
alert("Invalid");
}
}
</script>

70
Unit
Unit –– 5:
5: JS
JS 70
70 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
DHTML – Combining HTML,CSS & JS

• DHTML, or Dynamic HTML, is really just a


combination of HTML, JavaScript and CSS.
• The main problem with DHTML, which was
introduced in the 4.0 series of browsers, is
compatibility.
• The main focus generally when speaking of
DHTML is animation and other such dynamic
effects.

71
Unit
Unit –– 5:
5: JS
JS 71
71 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
DHTML (Cont)
• We can obtain reference of any HTML or CSS element in
JavaSCript using below 3 methods.
1. document.getElementById(“IdOfElement”)
2. document.getElementsByName(“NameOfElement”)
3. document.getElementsByTagName(“TagName”)
• After obtaining the reference of the element you can change the
attributes of the same using reference.attribute syntax
• For Example :

HTML Code JS Code

<img src=“abc.jpg” id=“myImg”> <script>


var a = document.getElementById(‘myImg’);
a.src = “xyz.jpg”;
</script>
72
Unit
Unit –– 5:
5: JS
JS 72
72 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
DHTML (Cont) (Example)
JavaScript
<html>
<body>
<div id=“myDiv”>
Red Alert !!!!!!
</div>
<script>
var objDiv = document.getElementById(“myDiv”);
var colors = [‘white’,’yellow’,’orange’,’red’];
var nextColor = 0;
setInterval(“objDiv.style.backgroundColor = colors[nextColor++%colors.length];”,500);
</script>
</body>
</html>

73
Unit
Unit –– 5:
5: JS
JS 73
73 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HTML Element Properties
Event Description
className Sets or returns the class attribute of an element
id Sets or returns the id of an element
innerHTML Sets or returns the HTML contents (+text) of an element
style Sets or returns the style attribute of an element
tabIndex Sets or returns the tab order of an element
title Sets or returns the title attribute of an element
value Sets or returns the value attribute of an element

74
Unit
Unit –– 5:
5: JS
JS 74
74 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Mouse Events
Event Attribute Description
click onclick The event occurs when the user clicks on an
element
dblclick ondblclick The event occurs when the user double-clicks on
an element
mousedown onmousedown The event occurs when a user presses a mouse
button over an element
mousemove onmousemove The event occurs when a user moves the mouse
pointer over an element
mouseover onmouseover The event occurs when a user mouse over an
element
mouseout onmouseout The event occurs when a user moves the mouse
pointer out of an element
mouseup onmouseup The event occurs when a user releases a mouse
button over an element

75
Unit
Unit –– 5:
5: JS
JS 75
75 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Keyboard Events
Event Attribute Description
keydown onkeydown The event occurs when the user is pressing a key
or holding down a key
keypress onkeypress The event occurs when the user is pressing a key
or holding down a key
keyup onkeyup The event occurs when a keyboard key is
released

76
Unit
Unit –– 5:
5: JS
JS 76
76 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Frame/Object Events
Event Attribute Description
abort onabort The event occurs when an image is stopped from
loading before completely loaded (for <object>)
error onerror The event occurs when an image does not load
properly (for <object>, <body> and <frameset>)
load onload The event occurs when a document, frameset, or
<object> has been loaded
resize onresize The event occurs when a document view is
resized
scroll onscroll The event occurs when a document view is
scrolled
unload onunload The event occurs when a document is removed
from a window or frame (for <body> and
<frameset>)

77
Unit
Unit –– 5:
5: JS
JS 77
77 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Form Events
Event Attribute Description
blur onblur The event occurs when a form element loses
focus
change onchange The event occurs when the content of a form
element, the selection, or the checked state have
changed (for <input>, <select>, and <textarea>)
focus onfocus The event occurs when an element gets focus
(for <label>, <input>, <select>, textarea>, and
<button>)
reset onreset The event occurs when a form is reset
select onselect The event occurs when a user selects some  text
(for <input> and <textarea>)
submit onsubmit The event occurs when a form is submitted

78
Unit
Unit –– 5:
5: JS
JS 78
78 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology

You might also like