SlideShare a Scribd company logo
1 of 78
Chapter 3:
JavaScript (JS)
Outline
2
 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
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
4
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
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
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
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
Server Side Scripting Client Side Scripting
Server side scripting is used to create
dynamic pages based on a number of
conditions when the users browser makes a
request to the server.
Client side scripting is used when the users
browser already has all the code and the
page is altered on the basis of the users
input.
The Web Server executes the server side
scripting that produces the page to be sent
to the browser.
The Web Browser executes the client side
scripting that resides at the user’s computer.
Server side scripting is used to connect to
the databases and files that reside on the
web server.
Client side scripting cannot be used to
connect to the databases and files on the
web server.
Client V/S Server Side Scripting
8
Server Side Scripting Client Side Scripting
Server resources can be accessed by the
server side scripting.
Browser resources can be accessed by the
client side scripting.
Server side scripting can’t be blocked by the
user.
Client side scripting is possible to be blocked
by the user.
Examples of Server side scripting languages :
PHP, JSP, ASP, ASP.Net, Ruby, Perl and many
more.
Examples of Client side scripting languages :
Javascript, VB script, etc.
Client V/S Server Side Scripting (Cont)
9
0
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 HTMLAttributes
<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>
12
Code
<html>
<head>
<title>HTML script Tag</title>
</head>
<body>
<script type="text/javascript">
// Java Script Code Here
</script>
</body>
</html>
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)
15
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>
JavaScript Output /JavaScript Display Possibilities
16
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().
window.alert()
alert.html
17
 You can use an alert box to
display data:
 Example
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
 For testing purposes, it is convenient to
use document.write():
 Example
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write()
write.html
Using innerHTML
18
 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
<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
innerHTML.html
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
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
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
JavaScript Operators
23
 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
JavaScript Comparison Operators
24
Operator Description Example
== Is equal to 10==20 = false
=== Identical (equal and
of same type)
10==20 = false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or
equal to
20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false
 The JavaScript comparison operator compares the two operands.
 The comparison operators are as follows:
JavaScript Logical Operators
25
Operator Description Example
&& Logical AND (10==20 &&
20==33) = false
|| Logical OR (10==20 ||
20==33) = false
! Logical Not !(10==20) = true
The following operators are known as JavaScript logical operators.
JavaScript Assignment Operators
26
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
The following operators are known as JavaScript assignment
operators.
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
28
If condition
if (condition) {
block of code to be executed
if the condition is true
}
switch
switch(expression)
{
case lbl1:
// code to execute
break;
case lbl2:
// code to execute
break;
}
The else Statement
if (condition) {
block of code to be executed if the
condition is true
} else {
block of code to be executed if the
condition is false
}
Loops
29
for loop
Use when you know how
many repetitions you want
to do
syntax
for(initialize ; condition ;
increment) { … }
example
for(x=0;x<10;x++) {
// Code Here
}
while loop
Loops through block of code
while condition is true
syntax
while(condition) { … }
example
while (x<10) {
//Code Here
}
do while loop
Execute block at least once
then repeat while condition
is true
syntax
do{ … } while (condition);
example
do{
// Code Here
} while (x<10)
Loops can execute a block of code a number of times.
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
31
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>
32
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.
Array Methods
 .
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 :
33
Code
function myFunction(p1, p2) {
return p1 * p2;
}
34
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.
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
example
36
<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>
</body>
Output:
This example calls a function which performs a calculation, and returns the result:
12
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
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.
38
Code
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<script>
alert("Hello World");
</script>
</body>
</html>
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 :
39
Code
<script>
var a = confirm(“Are you sure??");
if(a==true) {
alert(“User Accepted”);
}
else {
alert(“User Cancled”);
}
</script>
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.
40
Code
<script>
var a = prompt(“Enter Name");
alert(“User Entered ” + a);
</script>
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
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
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
User - Defined Objects (Cont.)
• However, it is also possible to assign values
when it is made with literal values.
44
example
<script>
person={
firstname: "Darshan",
lastname: "College",
age: 50,
eyecolor: "blue"
}
alert(person.firstname + " is " + person.age + " years old.");
</script>
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.
• Any properties inside the newly created object
are assigned using this keyword, referring to
the current object being created.
45
example
<script>
function person(firstname, lastname, age){
this.firstname = firstname;
this.lastname = lastname;
this. changeFirstName = function (name){ this.firstname = name };
}
var person1=new person("Narendra","Modi",50);
person1.changeFirstName(“NAMO”);
alert(person1.firstname + “ ”+ person1.lastname);
</script>
Handling Events and Exception Handling
46
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.
onclick Event Type
47
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>
</body>
onsubmit Event type
48
 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>
</body>
Exception handling
49
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
Syntax
50
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
The finally Statement
The finally statement lets you execute
code, after try and catch, regardless of the
result:
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
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
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.
52
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 side objects are connected to the
window object.
53
window
self,
parent,
window,
top
frames[] navigator location history document screen
54
What is the HTML DOM?
55
 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
JavaScript HTML DOM - Changing HTML
56
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>
</html>
JavaScript HTML DOM - Changing HTML
57
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>
JavaScript HTML DOM - Changing HTML
58
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>
 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
domain
Returns the domain name of the server that loaded the
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)
referrer
Returns the URL of the document that loaded the current
document
title Sets or returns the title of the document
URL Returns the full URL of the document
Methods of document object
60
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.
We can access and change the contents of document by its
methods.
DOM Document methods for finding HTML elements
getElementById()
 returns the element of specified id.
 Example :
61
<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>
getElementsByName()
• returns all the element of specified name.
• The syntax of the getElementsByName() method is given :
document.getElementsByName("name")
• Example :
62
<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>
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 :
63
<script type="text/javascript">
functtotalh2=document.getElementsByTagNam
e("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName
("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2<
/button>
<button onclick="counth3()">count h3<
/button>
ion counth2(){
var
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
64
<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>
</form>
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
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
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
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
RegExp (Cont.) (Quantifiers)
69
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
Email Validation Using RegExp
70
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>
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
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 :
72
HTML Code
<img src=“abc.jpg” id=“myImg”>
JS Code
<script>
var a = document.getElementById(‘myImg’);
a.src = “xyz.jpg”;
</script>
DHTML (Cont) (Example)
73
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>
HTML Element Properties
74
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
Mouse Events
75
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
Keyboard Events
76
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
Frame/Object Events
77
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>)
Form Events
78
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

More Related Content

Similar to CHAPTER 3 JS (1).pptx

Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students shafiq sangi
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scriptingpkaviya
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academyactanimation
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using JavascriptBansari Shah
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTAAFREEN SHAIKH
 
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptxMYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptxArjayBalberan1
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascriptambuj pathak
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentationJohnLagman3
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxrish15r890
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)SANTOSH RATH
 
BEAAUTIFUL presentation of java
BEAAUTIFUL  presentation of javaBEAAUTIFUL  presentation of java
BEAAUTIFUL presentation of javarana usman
 

Similar to CHAPTER 3 JS (1).pptx (20)

Html JavaScript and CSS
Html JavaScript and CSSHtml JavaScript and CSS
Html JavaScript and CSS
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
 
Java script
Java scriptJava script
Java script
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptxMYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
MYSQL DATABASE INTRODUCTION TO JAVASCRIPT.pptx
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
Lecture-15.pptx
Lecture-15.pptxLecture-15.pptx
Lecture-15.pptx
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptx
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
 
BEAAUTIFUL presentation of java
BEAAUTIFUL  presentation of javaBEAAUTIFUL  presentation of java
BEAAUTIFUL presentation of java
 
Java scipt
Java sciptJava scipt
Java scipt
 

Recently uploaded

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 

Recently uploaded (20)

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 

CHAPTER 3 JS (1).pptx

  • 2. Outline 2  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
  • 3. 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.
  • 4. client side scripting language vs Server side scripting 4 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. Server Side Scripting Client Side Scripting Server side scripting is used to create dynamic pages based on a number of conditions when the users browser makes a request to the server. Client side scripting is used when the users browser already has all the code and the page is altered on the basis of the users input. The Web Server executes the server side scripting that produces the page to be sent to the browser. The Web Browser executes the client side scripting that resides at the user’s computer. Server side scripting is used to connect to the databases and files that reside on the web server. Client side scripting cannot be used to connect to the databases and files on the web server. Client V/S Server Side Scripting 8
  • 9. Server Side Scripting Client Side Scripting Server resources can be accessed by the server side scripting. Browser resources can be accessed by the client side scripting. Server side scripting can’t be blocked by the user. Client side scripting is possible to be blocked by the user. Examples of Server side scripting languages : PHP, JSP, ASP, ASP.Net, Ruby, Perl and many more. Examples of Client side scripting languages : Javascript, VB script, etc. Client V/S Server Side Scripting (Cont) 9 0
  • 10. 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:
  • 11. 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 HTMLAttributes
  • 12. <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> 12 Code <html> <head> <title>HTML script Tag</title> </head> <body> <script type="text/javascript"> // Java Script Code Here </script> </body> </html>
  • 13. 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>
  • 14. 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>
  • 15. External JavaScript (Example) 15 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>
  • 16. JavaScript Output /JavaScript Display Possibilities 16 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().
  • 17. window.alert() alert.html 17  You can use an alert box to display data:  Example <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body>  For testing purposes, it is convenient to use document.write():  Example <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(5 + 6); </script> </body> </html> Using document.write() write.html
  • 18. Using innerHTML 18  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 <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 innerHTML.html
  • 19. 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 )
  • 20. 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
  • 21. 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
  • 22. 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
  • 23. JavaScript Operators 23  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
  • 24. JavaScript Comparison Operators 24 Operator Description Example == Is equal to 10==20 = false === Identical (equal and of same type) 10==20 = false != Not equal to 10!=20 = true !== Not Identical 20!==20 = false > Greater than 20>10 = true >= Greater than or equal to 20>=10 = true < Less than 20<10 = false <= Less than or equal to 20<=10 = false  The JavaScript comparison operator compares the two operands.  The comparison operators are as follows:
  • 25. JavaScript Logical Operators 25 Operator Description Example && Logical AND (10==20 && 20==33) = false || Logical OR (10==20 || 20==33) = false ! Logical Not !(10==20) = true The following operators are known as JavaScript logical operators.
  • 26. JavaScript Assignment Operators 26 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 The following operators are known as JavaScript assignment operators.
  • 27. 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
  • 28. Conditions 28 If condition if (condition) { block of code to be executed if the condition is true } switch switch(expression) { case lbl1: // code to execute break; case lbl2: // code to execute break; } The else Statement if (condition) { block of code to be executed if the condition is true } else { block of code to be executed if the condition is false }
  • 29. Loops 29 for loop Use when you know how many repetitions you want to do syntax for(initialize ; condition ; increment) { … } example for(x=0;x<10;x++) { // Code Here } while loop Loops through block of code while condition is true syntax while(condition) { … } example while (x<10) { //Code Here } do while loop Execute block at least once then repeat while condition is true syntax do{ … } while (condition); example do{ // Code Here } while (x<10) Loops can execute a block of code a number of times.
  • 30. 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
  • 31. 31 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>
  • 32. 32 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. Array Methods  .
  • 33. 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 : 33 Code function myFunction(p1, p2) { return p1 * p2; }
  • 34. 34 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.
  • 35. 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
  • 36. example 36 <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> </body> Output: This example calls a function which performs a calculation, and returns the result: 12
  • 37. 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
  • 38. 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. 38 Code <html> <head> <title>Alert Box</title> </head> <body> <script> alert("Hello World"); </script> </body> </html>
  • 39. 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 : 39 Code <script> var a = confirm(“Are you sure??"); if(a==true) { alert(“User Accepted”); } else { alert(“User Cancled”); } </script>
  • 40. 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. 40 Code <script> var a = prompt(“Enter Name"); alert(“User Entered ” + a); </script>
  • 41. 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
  • 42. 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
  • 43. 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
  • 44. User - Defined Objects (Cont.) • However, it is also possible to assign values when it is made with literal values. 44 example <script> person={ firstname: "Darshan", lastname: "College", age: 50, eyecolor: "blue" } alert(person.firstname + " is " + person.age + " years old."); </script>
  • 45. 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. • Any properties inside the newly created object are assigned using this keyword, referring to the current object being created. 45 example <script> function person(firstname, lastname, age){ this.firstname = firstname; this.lastname = lastname; this. changeFirstName = function (name){ this.firstname = name }; } var person1=new person("Narendra","Modi",50); person1.changeFirstName(“NAMO”); alert(person1.firstname + “ ”+ person1.lastname); </script>
  • 46. Handling Events and Exception Handling 46 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.
  • 47. onclick Event Type 47 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> </body>
  • 48. onsubmit Event type 48  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> </body>
  • 49. Exception handling 49 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
  • 50. Syntax 50 try { Block of code to try } catch(err) { Block of code to handle errors } The finally Statement The finally statement lets you execute code, after try and catch, regardless of the result: 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
  • 51. 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
  • 52. 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. 52
  • 53. 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 side objects are connected to the window object. 53 window self, parent, window, top frames[] navigator location history document screen
  • 54. 54
  • 55. What is the HTML DOM? 55  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
  • 56. JavaScript HTML DOM - Changing HTML 56 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> </html>
  • 57. JavaScript HTML DOM - Changing HTML 57 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>
  • 58. JavaScript HTML DOM - Changing HTML 58 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>
  • 59.  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 domain Returns the domain name of the server that loaded the 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) referrer Returns the URL of the document that loaded the current document title Sets or returns the title of the document URL Returns the full URL of the document
  • 60. Methods of document object 60 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. We can access and change the contents of document by its methods. DOM Document methods for finding HTML elements
  • 61. getElementById()  returns the element of specified id.  Example : 61 <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>
  • 62. getElementsByName() • returns all the element of specified name. • The syntax of the getElementsByName() method is given : document.getElementsByName("name") • Example : 62 <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>
  • 63. 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 : 63 <script type="text/javascript"> functtotalh2=document.getElementsByTagNam e("h2"); alert("total h2 tags are: "+totalh2.length); } function counth3(){ var totalh3=document.getElementsByTagName ("h3"); alert("total h3 tags are: "+totalh3.length); } </script> <h2>This is h2 tag</h2> <h2>This is h2 tag</h2> <h3>This is h3 tag</h3> <h3>This is h3 tag</h3> <h3>This is h3 tag</h3> <button onclick="counth2()">count h2< /button> <button onclick="counth3()">count h3< /button> ion counth2(){ var
  • 64. 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 64 <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> </form>
  • 65. 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
  • 66. 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
  • 67. 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
  • 68. 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
  • 69. RegExp (Cont.) (Quantifiers) 69 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
  • 70. Email Validation Using RegExp 70 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>
  • 71. 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
  • 72. 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 : 72 HTML Code <img src=“abc.jpg” id=“myImg”> JS Code <script> var a = document.getElementById(‘myImg’); a.src = “xyz.jpg”; </script>
  • 73. DHTML (Cont) (Example) 73 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>
  • 74. HTML Element Properties 74 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
  • 75. Mouse Events 75 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
  • 76. Keyboard Events 76 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
  • 77. Frame/Object Events 77 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>)
  • 78. Form Events 78 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