0% found this document useful (0 votes)
8 views65 pages

Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views65 pages

Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Client Side Scripting

Introduction to Client Side Scripting


Topics to be covered
• What is Client Side Scripting?
• Client Side Processes
• JavaScript
• Applications of JavaScript
• Where to embed a script?
Introduction
• What is Client Side Scripting?
Client-side scripting simply means running scripts, such as JavaScript, on the client device, usually
within a browser. All kinds of scripts can run on the client side if they are written in JavaScript,
because JavaScript is universally supported. Other scripting languages can only be used if the user's
browser supports them.
- Scripting provides static HTML pages the ability to make decisions and to perform operations
- Scripts are codes embedded in HTML pages
- Scripts are executed by the browser when the user performs an action such as clicking a button
What is Client side?
'Client side' refers to everything in a web application that is displayed or
takes place on the client (end user device). This includes what the user
sees, such as text, images, and the rest of the UI, along with any actions
that an application performs within the user's browser.
Let us try and understand what client side is with the help of the
following example.
The HTML, CSS, and JavaScript that dictate how the Netflix main page
appears to the user are interpreted by the browser on the client side. The
page can also respond to 'events': For instance, if the user's mouse
hovers over one of the movie thumbnail images, the image expands and
adjacent thumbnails move slightly to one side to make room for the
larger image. This is an example of a client-side process; the code within
the webpage itself responds to the user's mouse and initiates this action
without communicating with the server.
Client Side Processes
• Data Validation
• Item Selection
• Form Submission
• Keyboard and Mouse Events
• Animation
JavaScript
• Scripting language which is used to enhance the functionality and appearance of web pages.
• It is considered as the de facto standard client-side scripting language for web-based applications due to its highly portable
nature.
• Many people confuse the scripting language JavaScript with the programming language Java. Java is a full-fledged object-
oriented programming language. Java is popular for developing large-scale distributed enterprise applications and web
applications. JavaScript is a browser-based scripting language developed by Netscape and implemented in all major
browsers.
• Before you can run code examples with JavaScript on your computer, you may need to change your browser’s security
settings.
• IE9 prevents scripts on the local computer from running by default. Firefox, Chrome, Opera, Safari (including on the
iPhone) and the Android browser have JavaScript enabled by default.
Applications of JavaScript
JavaScript gives HTML designers a programming tool
JavaScript has a simple syntax! Almost anyone can put small "snippets" of code into their HTML pages
• JavaScript can put dynamic text into an HTML page
Example: document.write("<h1>" + name + "</h1>") can write a variable text from “name” into an HTML page
• JavaScript can react to events
A script can be set to execute when an event occurs such as when a page has finished loading or when a user clicks on
an HTML element
• JavaScript can read and write HTML elements
JavaScript can read and change the content of an HTML element
• JavaScript can be used to validate data
Scripts can be used to validate form data before it is submitted to a server. This saves the server from extra processing
• JavaScript can be used to detect the visitor's browser
Depending on the browser, the script can load another page specifically designed for that browser
• JavaScript can be used to create cookies
Scripts can be used to store and retrieve information on the visitor's computer
Where to embed a script?
In document head <head>...</head>
– Used when scripts are written as functions to be executed on function calls when an event is triggered
– Placing a script in the head section, ensures that the script is loaded before any other part of the page uses it
Example:
<head>
<script language=“javascript” type="text/javascript">
....
</script>
</head>

In document body <body>...</body>


– Used when a script generates the content of a page
– Such scripts are executed when the document body is created
Example:
<body>
<script language=“javascript” type="text/javascript">
....
</script>
</body>
<script> tag
The HTML <script>...</script> tag is used to insert JavaScript into an HTML page.
<html>
<body>
<script language = “javascript” type="text/javascript">
document.write("<h1>Hello World!</h1>");
</script>
</body>
</html>
NOTE: HTML tag <h1> used within the script.
The browser will interpret the script as:
<body>
<h1>Hello World!</h1>
</body>

The language attribute explicitly informs the browser that the enclosed code is JavaScript
•The type attribute specifies that the code is in text format
• ’document’ refers to the body of an HTML document defined by <body>...</body> tags
• ’write’ is a method used for writing output to a page
• The browser recognizes the lines between the <script>...</script> tags as JavaScript code and executes it
External Script file
Including script as an external file is helpful
– If you want to use the same script on several pages
– If the script code is complex
– If the code is likely to be revised often
– To protect (though partly!) precious code
Guidelines to create and use script files
– Save the external JavaScript file with a .js file extension
– The external file cannot contain the <script> tag!
– Use the "src" attribute of the <script> tag to include the script file
– Place the script exactly where you normally would write it
Example:
<head><script type="text/javascript" src=“myScript.js"> </script>
</head>
Syntax and Functions of Client Side Scripting
Topics to be covered
• Variables
• Arithmetic, Assignment, Relational and Logical operators
• Selection control structures
Variables
- Definition
- Rules for JavaScript Variable Names
- Variable Declaration
Variables
Variables are storage areas used to hold data values
• A variable's value can change during the execution of a script
• A variable must have a unique name
• You refer to a variable by its name to display or change its value.

• Rules for JavaScript variable names:


- Variable names are case sensitive (y and Y are two different variables).
- Variable names must begin with a letter or the underscore character.
- Variable names have to be unique.
Declaring Variables
• You can declare JavaScript variables with the var statement
var a;
var company;

After the declaration shown above, the variables are empty (they have no meaningful values yet).
You can also assign values to the variables when you declare them.
var a=5; //int value
var company=“Infosys"; //String value
Operators
• Arithmetic
• Assignment
• Logical
• Relational
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or constants.
Given that y=5, the table below explains the arithmetic operators

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus x=y%2 x=1
++ Increment(pre and post) x=++y x=6, y=6
-- Decrement(pre and post) x=y-- x=5, y=4
JavaScript Assignment Operators
Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators

Operator Example Same as Result


= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
JavaScript Logical Operators
Logical operators are used to determine the logic between relational expressions
Given that x=6 and y=3, the table below explains the logical operators

Operator Description Example


&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true
JavaScript Relational Operators
Relational operators are used to compare two values.
Given that x=5, the table below explains the relational operators

Operator Example Description


== is equal to (any type) x==8 is false
=== is exactly equal to (value and type) x===5 is true , x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true
String Operator(+)
The + operator can also be used to join together
(concatenate) string variables or text values
Example 1:
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
Variable txt3 contains "What a verynice day".
Example 2:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
Variable txt3 contains "What a very nice day"
Concatenation
When the “ + “ operator is used on a numeric and a string operand, the number is concatenated to the string operand and the
resultant value is a string
<html>
<head><title>JavaScript</title></head>
<body><h1>example</h1>
<script language="javascript">
var x;
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
</script></body></html>
Decision Making Statements
• if statement
• If-else statement
• switch statement
if statement
if statement executes some code only if a specified condition is true.

Syntax
if (condition)
{
// code to be executed if condition is true
}
• When JavaScript encounters an if statement, it checks the condition.
• If and only if, the condition is found to be true, the statements enclosed within the curly braces are
executed.
if else statement
Each condition has two paths from which we choose one.
For example, "If it's raining, I'll stay at home else I'll go out for a stroll.“
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
Switch statement
Using the switch statement, we can select one of many blocks of code to be executed.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is other than case 1
and 2
}
Functions of Client Side Scripting
Topics to be covered
• User defined functions (Definition,Syntax)
• Conversion Functions(parseInt,parseFloat,isNaN)
• alert(),prompt(),confirm() methods
• Local and Global Variables
• Events and Event Handlers
- JavaScript Events
(click, change, focus, load, mouseOver, mouseOut, select, blur)
- JavaScript Event Handlers
(onClick, onMouseOver, onMouseOut, onChange, onFocus, onBlur, onSelect)
Functions
A function is a block of code that performs a single, related action.
Functions can be of two types
- Built-in
- User-defined
Syntax of user-defined functions:
function fnName(parameterlist)
{
// body of function
}
User Defined functions
• A function consists of the function keyword, name of the function, parameters (if any) and JavaScript
statement/s
• Functions are placed in the head section of the HTML document. This ensures that a function is loaded by the
browser before it is called.
• Function calls can occur in any part of the document and even inside event handler code.
• A return statement is used to transfer control out of a function or to return a value.
User Defined Functions
<html>
<head> <title>Functions</title>
<script language="javascript" type="text/javascript">
<!--
function alert_box(msg)
{
document.bgColor="#EEEEEE";
alert(msg);
}
// -->
</script> </head>
<body>
<script language="javascript" type="text/javascript">
<!--
alert_box("Welcome to Goa");
// -->
</script> </body></html>
Conversion Functions
For parseInt()and parseFloat() to work correctly, the string must be composed entirely of digits.
parseInt() - Converts a string to an integer value
parseFloat() - Converts a string to a floating point number
•When parseInt()or parseFloat()encounters an alphabet or any non-digit character, parsing (conversion) stops
and the function returns NaN,which means Not a Number.
•This can be tested using isNaN() function
var n = prompt("Check your number", "");
n = parseInt(n);
if (isNaN(n))
{
alert("The input cannot be parsed to a number");
}
alert(),prompt(),confirm()
These are methods of the window object
•Used to interact with the user
•When executed, each method displays a message box having a specific purpose
•The methods take a string (say messageText) as parameter
•messageText must be a valid JavaScript string
alert()
Syntax:
alert(messageText);
•Displays a message box with messageText as the message
Example:
alert(“This is an alert Box");
•Useful in
– Making outputs
– Debugging JavaScript code
confirm()
Syntax:
confirm(messageText);
• Displays a message box with “messageText” as the message and an "OK" and a "Cancel" button
Example:
confirm ("Do you wish to continue?");
• When the user clicks on "OK" the value 'true' is returned, while clicking on "Cancel" returns 'false’
• We can capture this returned value in a variable and test it through an if statement
prompt()
Syntax:
prompt(messageText, response);
•In addition to the message and "OK" and "Cancel" buttons, a prompt box also has a text field for gathering user input
•JavaScript lets you specify a default text for the text field through the response parameter. The response parameter is optional.
•Example:
prompt ("Enter day: ", "Tuesday"); // default response –"Tuesday"
prompt ("Enter day: ", ""); // for empty textbox
Response submitted by the user can be stored in a variable
•This value will always be of string data type
•If you want to receive numeric data through prompt(), JavaScript provides two functions to convert string value to a numeric value
–parseInt()
•Converts a string to an integer value
–parseFloat()
•Converts a string to a floating point number
Local and Global Variables
Variables created inside a function are called Local variables. They have no
presence outside the function.
- Values of local variables cannot be changed by the main code or other functions.
- Variables that are created outside any function are called Global variables.
- Their values are available anywhere in the code and to all functions
Events and Event Handlers
Event is an action that occurs when a user interacts with a Web page such as
–Moving the mouse over text
–Clicking a button
To make interactive pages you need to catch or recognize the events.
Event handler is a subroutine associated with an HTML element to capture an event.
An event handler calls a JavaScript function in response to an event.
JavaScript Events
Event Description
click Generated when a user clicks on a form element or on a link
change Generated when a user changes the value of a form field
focus Generated when a user gives input to a form element
load Generated when a page is loaded into the browser
mouseOver Generated when a user moves the mouse pointer over a link or area object
mouseOut Generated when the mouse pointer leaves the link or area object
select Generated when a user selects a form field
blur Generated when the input focus is removed from a form
JavaScript Event Handlers
Object Event Handler
Button onClick
Reset onClick
Submit onClick
Radio onClick
CheckBox onClick
Link onClick, onMouseOver and onMouseOut
Form onSubmit and onReset
Text onChange, onFocus, onBlur and onSelect
TextArea onChange, onFocus, onBlur and onSelect
Select onChange, onFocus and onBlur
Image onAbort and onError
Area onClick, onMouseOver and onMouseOut
Window onLoad, onUnLoad and onError
JavaScript Loops
Loops are used to execute blocks of code repeatedly
There are three types of looping constructs:
a) for loop
b) while loop
c) do...while loop
for Loop
Syntax
for (Initialization; Condition; Update statements)
{
... body of loop ...
}
Steps in loop execution
– When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the
condition.
– Only if the condition returns 'true', the interpreter enters the loop.
– After each iteration, the update statements are executed and the condition is evaluated again.
– The loop stops when the condition returns 'false'.
while Loop
Syntax
while (condition)
{
...statements...
…including update statement…
}
- As long as the condition evaluates to 'true', the program execution will continue to loop through the
statements.
- If the condition in while evaluates to 'false' at the beginning itself, the loop is skipped altogether and program
execution starts at the statement immediately following the loop.
do while Loop
Syntax
do
{
...statements...
…including update statement…
} while (condition);
As long as the condition evaluates to 'true', the program execution will continue to loop through the
statements.
Here, the condition is placed at the end of the loop and hence, the loop is executed at least once.
Document Object Model
Topics to be covered
• DOM Hierarchy
• Accessing elements in a DOM tree
• DOM Identifiers and Methods
Document Object Model
The DOM gives you scripting access to all the elements on a web page. Inside the browser, the whole web page
—paragraphs, forms, tables, etc.—is represented in an object hierarchy. Using JavaScript, you can dynamically
create, modify and remove elements in the page.
Document Object Model
A hierarchy demonstrates the principle of containership
•Lower-level objects are contained within top-level objects
•In order to reference a lower-level object, we also need to reference its parent or container object
•JavaScript uses the dot (.) to separate the parent object from its components
In DOM, documents have a logical structure which is very much like a tree; to be more precise, which
is like a "forest" or "grove", which can contain more than one tree. Each document contains zero or one
doctype nodes, one root element node, and zero or more comments or processing instructions; the root
element serves as the root of the element tree for the document. However, the DOM does not specify that
documents must be implemented as a tree or a grove, nor does it specify how the relationships among
objects be implemented.
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Changing HTML Elements
Property Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element
Adding and Deleting HTML elements

Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
Adding Event Handlers

Method Description
document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event
Sample Codes
How to use getElementById()
<html>
<head>
<title>Introduction to Objects</title>
<script type="text/javascript">
//DOM Manipulation and getElementById Method//
function buttonClick()
{
document.getElementById("heading2").innerHTML=“This is new text ";
}
</script>
</head>
<body>
<button onclick="buttonClick()">Click me</button>
<h2 id="heading2">Some Random Text</h2>
</body>
</html>
How to use getElementsByClassName()
<html>

<head>

<title>DOMS using JS</title>

<script type="text/javascript">

function styleChange()

var para = document.getElementsByClassName("pt");

for(var i = 0; i < para.length; i++)

para[i].style.fontSize = 24;

para[i].style.fontWeight = "bold";

para[i].style.fontStyle = "italic";

</script>

</head>

<body bgcolor = "black">

<p class = "a" style = "color:tomato">#1 Paragraph</p>

<p class = "pt" style = "color:tomato">#2 Paragraph</p>

<p class = "a" style = "color:tomato">#3 Paragraph</p>

<p class = "pt" style = "color:tomato">#4 Paragraph</p>

<button onclick = "styleChange()" name = "Submit">Change Style</button>

</body>

</html>
How to use getElementByTagName
<html>
<head>
<title>DOMS using JS</title>
<script type="text/javascript">
function styleChange()
{
var para = document.getElementsByTagName("p");
for(var i = 0; i < para.length; i++)
{
para[i].style.fontSize = 24;
para[i].style.fontWeight = "bold";
para[i].style.fontStyle = "italic";
}
}
</script>
How to use getElementByTagName

</head>
<body bgcolor = "black">
<p style = "color:tomato">#1 Paragraph</p>
<p style = "color:tomato">#2 Paragraph</p>
<p style = "color:tomato">#3 Paragraph</p>
<p style = "color:tomato">#4 Paragraph</p>
<p style = "color:tomato">#5 Paragraph</p>
<button onclick = "styleChange()" name = "Submit">Change Style</button>
</body>
</html>
Creating Form Elements using DOM

<html>
<head>
<title>DOMS using JS</title>
<script type="text/javascript">
function create()
{
mdiv = document.getElementById("a");
sel = document.createElement("Select");
op1 = document.createElement("Option");
op2 = document.createElement("Option");
op3 = document.createElement("Option");
tn1 = document.createTextNode(“Suzuki");
tn2 = document.createTextNode(“Toyota");
tn3 = document.createTextNode(“Hyundai");
Creating Form Elements using DOM

op1.appendChild(tn1);
op2.appendChild(tn2);
op3.appendChild(tn3);
sel.appendChild(op1);
sel.appendChild(op2);
sel.appendChild(op3);
mdiv.appendChild(sel);
}
</script>
</head>
<body bgcolor = "black">
<input type="button" value="Click" onclick="create();">
<br><br>
<div id = "a"> </div>
</body>
</html>
Validation
- Required Field Validator
- Check Number Validation
- Email Validation
- Checkbox and Radio Button Validation
- Drop Down list Validation
JavaScript Form Validation
JavaScript can be used to validate data in
HTML forms before sending off the content to
a server.
• Form data that typically are checked by a
JavaScript could be:
1. has the user left required fields empty?
2. has the user entered a valid e-mail address?
3. has the user entered a valid date?
4. has the user entered text in a numeric field?
Required Field Validator
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false
and the form will not be submitted:
<html>
<head>
<script>
function validateForm()
{
var x=document.myForm.fname.value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.php" onsubmit="return validateForm()“ method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
E-mail Validation
The function below checks if the content has the general syntax of an email.
1. This means that the input data must contain an @ sign and at least one dot (.)
eg: [email protected] ; [email protected]
2. the @ must not be the first character of the email address
3. the last dot must be present after the @ sign
4. minimum 2 characters before the end
E-mail Validation
<html>
<head><script>
function validateForm()
{
var x=document.myForm.email.value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script></head>
<body>
<form name="myForm" action="demo_form.php" onsubmit="return validateForm();"
method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body></html>
Check Number
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format ######" );
document.myForm.Zip.focus() ;
return false;
}

Code in the <body>


Zip Code :<input type="text" name="Zip" />
Dropdown List
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );

Code in <body>
<select name="Country">
<option value="-1" selected>Select country</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
Checkbox & Radio button

If(document.myForm.mycheckbox.checked == false)
{
alert(“Please select a value");
return false;
}
Question Bank
1) Write a note on the DOM Hierarchy.
2) What are Events and Event Handlers?
3) Name any 2 Validations and write a JavaScript function for the same .
4) List 3 rules to be followed while naming a JavaScript Variable.
5) Write a note on Client Side Scripting.
6) Differentiate between Java and JavaScript?
7) Name any 3 DOM identifiers and write a JavaScript function for the same .
8) List any 4 Applications of JavaScript.
9) What are local and global variables?
10) Name 2 conversion functions and explain in brief.
11) Explain in brief a) prompt() b) confirm()
12) List 4 Client Side Processes.

You might also like