SlideShare une entreprise Scribd logo
1  sur  124
Lecture -5
Javascript
Mujtaba Haider
Objectives
• Introduction to JavaScript
– Introduction to JavaScript programming language
– Using Script tag
– Inserting Java Script into tags
– Linking Java Script from separate files
• JavaScript expression and Operators
– Defining and naming variables
– Data Types
– Expression
– Operators – Arithmetic, String, Logical, Assignment,
typeof
Objectives (Contd.)
• Functions and Flow Control
– Flow Control
• If…else
• For loops
• while loops
• Break and continue statements
– Using JavaScript functions
• Built in functions
• User defined functions
• Returning values from functions
• Events, Event Handlers
Objectives (Contd.)
• Objects and Arrays
– Properties and Methods
– Browser Object Hierarchy
– Addressing Objects
– Creating Objects
– Objects and Variables
– External Objects
– Security Implications
– Arrays and Objects
Objectives (Contd.)
• Document Object Model
– Introduction to DOM
– The Navigator Object
– The Window Object
– Communicating between windows
– Working With Frames in the DOM
– The Document object
– The Location & History Object
– Image Object
– Link Object
Objectives (Contd.)
• Form Validation The Form Object Model
– Recap of Form Elements
– Form Tag Events
– Controlling Submission
– Forms as Navigation
– List Events
– Buttons
– Text Processing
Objectives (Contd.)
• Cookies
– Introduction to HTTP Cookies
– Formatting Cookies
– Persisting Cookies
– Cookie Security
– JavaScript & Cookies
– Reading / Writing Cookies
– Modifying and deleting Cookies
Introduction to Java Scripts
• What is JavaScript???
– JavaScript is a scripting Language created by
Netscape
What is a
Scripting
Language???
•Scripting Language is a lightweight
programming language.
• Scripting Languages are not
needed to be compiled.
•The language is interpreted at
runtime.
Introduction to JavaScript
(Contd.)
– A JavaScript is usually directly embedded in an
HTML page.
– External JavaScripts can be created which can be
used by HTML pages.
– JavaScript adds interactivity to HTML pages.
– JavaScript's are integrated into the browsing
environment.
Introduction to JavaScript
(Contd.)
Is
JavaScript
same as
Java???
• Java is a programming
language which requires
compilation and interpretation.
• Java is used to make large
scale applications.
• JavaScript is a scripting
language which just requires
interpretation. The script is
some set of commands which
the browser interprets.
• JavaScript is used to add
interactivity in HTML Pages.
Types of JavaScript
• Client-Side JavaScript (CSJS) -- an extended
version of JavaScript that enables the enhancement
and manipulation of web pages and client browsers.
• Server-Side JavaScript (SSJS) -- an extended
version of JavaScript that enables back-end access to
databases, file systems, and servers.
• Core JavaScript -- the base JavaScript language.
Core JavaScript
• Core JavaScript encompasses all of the statements,
operators, objects, and functions that make up the
basic JavaScript language.
• The following objects are part of core JavaScript:
– array
– date
– math
– number
– string
Client Side Java Scripting
• CSJS is composed of core JavaScript and many
additional objects, such as the following:
– document
– form
– frame
– window
– Navigator
– History
Server Side JavaScript
• SSJS is composed of core JavaScript and additional
objects and functions for accessing databases and file
systems, sending e-mail, and so on.
Uses of JavaScript (Client Side)
• Menus for Navigation
• Form Validation
• Popup Windows
• Password Protecting
• Math Functions
• Special effects with document and background
• Status bar manipulation
• Messages
• Mouse Cursor Effects
• Links
Syntax rules of JavaScript
• Statements may or may not contain a semicolon at the
end.
• Multiple statements on one line must be separated by a
semicolon.
• JavaScript is case sensitive.
Using <script> tag
• The HTML <script> tag is used to enter JavaScript into
a HTML.
• The <script> tag can be embedded within
– <head> tag.
– <body> tag.
• JavaScript in the head section will be executed when
called.
• JavaScript in the body section will be executed while
the HTML page is loaded.
• Unlimited number of JavaScript’s can be placed both in
head and body section in a HTML document.
Using <script> tag
Eg:
<html>
<head><title>Example</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Is a standard command for writing
output to a page
How to Handle Older Browsers
• Browsers that do not support JavaScript will display the
script as it is. Use the HTML comment tag to prevent
this.
Eg.
<script type="text/javascript">
<!--
document.write("Hello World!")
// -->
</script>
The two forward slashes at the end of comment line
(//) are a JavaScript comment symbol. This
prevents the JavaScript compiler from compiling
the line.
Using an External JavaScript
• A JavaScript can be written in an external file, which
can be used by different HTML pages.
• The external script cannot contain the <script> tag.
• The external file needs to end with the .js extension.
Using External JavaScript
(contd.)
document.write("This line
has been writen in the
External JavaScript!!!")
External.js
<html>
<head><title>Example</title>
</head>
<body>
<script src="External.js">
</script>>
<p >
This line has been written in the
html page!!!
</p>
</body>
</html>
JavaScript.html
JavaScript Variables and
expression
• JavaScript Variables
– Variable:
• A variable is a symbolic name that
represents some data in the memory.
• A variable value can change during the
execution of the JavaScript.
• A variable can be referred by its name
to see or change its value.
• Variables are name are case sensitive.
• Must begin with a letter or underscore.
Rules of a Variable
• Variable Declaration
– Variables can be declared using the var statement
var <variable name>=some value
– Variables can also be created without using var
statement
<variable name>=some value
– Eg
var firstname=“Samuel”
OR
firstname=“Samuel”
Data Type in JavaScript
• JavaScript is a loosely typed language.
• Data Type of Variable
need not be specified
during declaration.
• Data types are
automatically converted
during script execution.
Loosely
Typed??
Data Type in JavaScript (contd.)
• JavaScript recognizes the following type of values:
Values
string
numbers
null
boolean
9, 3.56
true or false
Samuel, ”Samuel J Palmisano”
A Special keyword which refers to
nothing
Data Type in JavaScript (contd.)
JavaScript Operators
Arithmetic Assignment
String
Comparison
Logical
Operators
typeof
JavaScript Operator (contd.)
Arithmetic
JavaScript Operator (contd.)
Comparison
JavaScript Operator (contd.)
Assignment
JavaScript Operator (contd.)
Logical
JavaScript Operator (contd.)
String
JavaScript Operator (contd.)
typeof
Flow Control
• Conditional Statements
– if statement - use this statement if you want to
execute some code only if a specified condition is
true.
– if...else statement - use this statement if you want
to execute some code if the condition is true and
another code if the condition is false.
– if...else if....else statement - use this statement if
you want to select one of many blocks of code to be
executed.
– switch statement - use this statement if you want
to select one of many blocks of code to be
executed.
while statement
break and continue Statements
• There are two special statements that can be used
inside loops:
– break.
– continue.
• Break
– The break command will break the loop and continue
executing the code that follows after the loop (if any).
• Continue
– The continue command will break the current loop and
continue with the next value.
Example of break statement
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=5;i++)
{ if (i==3){break}
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
Example of continue statement
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=5;i++)
{ if (i==3){continue}
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
For loop
Functions
• A function is a reusable piece of code that will be
executed when called for.
• A function can be called from anywhere from within the
page or even from other pages if the function is stored
in an external JavaScript (.js) file.
• Functions can be embedded in the <head></head> and
within the<body> </body> tag.
Predefined functions in JavaScript
• DialogBoxes
– alert( message)
Displays an alert box with a
message defined by the
string message.
Eg.
alert(“An Error Occurred!”)
Predefined functions in JavaScript
(contd.)
• confirm(message)
– When called, it will display the
message and two boxes. One
box is "OK" and the other is
"Cancel". If OK is selected, a
value of true is returned,
otherwise a value of false is
returned.
Eg.
confirm(“Do you wish to Continue?”)
Predefined functions in JavaScript
(contd.)
• prompt(message)
– Displays a box with the message passed to the function
displayed.
– The user can then enter text in the prompt field, and
choose OK or Cancel.
– If the user chooses Cancel, a NULL value is returned. If
the user chooses OK, the string value entered in the
field is returned.
Eg:
prompt(“enter your Name”)
Predefined functions in
JavaScript (contd.)
• Conversion Functions
– eval(string)
Converts a string to an integer or a float value.
Eg
x=“20”
y=eval(x)+10
y contains the value 30
Predefined functions in
JavaScript (contd.)
– isNaN(value)
If the value passed is not a number then a
boolean value of true is returned else the
boolean value of false is returned.
Eg
x=“Samuel”
y=isNaN(x)
The value stored in y is true
Predefined functions in
JavaScript (contd.)
– parseInt(string)
Converts a string to an integer returning the first
integer encountered which is contained in the
string.
Eg
x=77AB67
y=parseInt(x)
y stores the value 77
Predefined functions in
JavaScript (contd.)
– parseFloat(string)
Converts a string to an float value .
Eg
x=77.5AB67
y=parseFloat(x)
y stores the value 77.5
User Defined Functions
User Defined Functions (contd.)
User Defined Functions (contd.)
Events
Events (contd.)
Event Handlers
Common Event Handlers
(contd.)
• onLoad and onUnload
– The onload and onUnload events are triggered
when the user enters or leaves the page.
– The onload event is also triggered when the image
is loaded.
The showstatus() function will be called when a user enters a page
<body onload=“showStatus()”>
Common Event Handlers
(contd.)
• onFocus, onBlur and onChange
– The onFocus, onBlur and onChange events are
often used in combination with validation of form
fields.
The checkEmail() function will be called whenever the user changes the content of the field:
<input type="text" size="30" id="email"
onchange="checkEmail()">;
Common Event Handlers
(contd.)
• onSubmit
– The onSubmit event is used to validate ALL form
fields before submitting it.
The checkForm() function will be called when the user clicks the submit
button in the form.
<form method="post" action="xxx.htm" onsubmit="return checkForm()">
Common Event Handlers
(contd.)
• onMouseOver and onMouseOut
– onMouseOver and onMouseOut are often used to
create "animated" buttons.
An alert box appears when an onMouseOver event is
detected:
<a href="http://www.ibm.com" onmouseover="alert('An
onMouseOver event’)”> <img src=“ibmlogo.gif" width="100"
height="30"> </a>
Example
Example (contd.)
Example (contd.)
Example (contd.)
Example (contd.)
Example (contd.)
Example (contd.)
function Addition (x,y) {
var x1=parseInt(x)
var y1=parseInt(y)
var Ans=document.form1.text3.value
var temp=x1+y1
}
<Input type=“text” name=“text3” value=“”>
Example (contd.)
function Addition (x,y) {
var x1=parseInt(x)
var y1=parseInt(y)
var Ans=document.form1.text3.value
var temp=x1+y1
}
<INPUT TYPE=“button” value=“ +op “
onClick=“Addition(text1.value,text2.value)”>
Example (contd.)
FaaDoOEngineers.com
function Addition (x,y) {
var x1=parseInt(x)
var y1=parseInt(y)
var Ans=document.form1.text3.value
var temp=x1+y1
if(Ans==temp){
alert(“Your Result agrees with JavaScript!”)
document.form1.text1.value=‘’
document.form1.text2.value=‘’
document.form1.text3.value=‘’
}
else{
alert(“No, JavaScript evalutes this operation differently”)
document.form1.text3.value=‘’
}}
<Form name=“form1” Method=“post” action=“url”
onSubmit=“return validate()>
<Input type=“text” name=“text1” value=“”>
A Complete Program
<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button"
onClick="myfunction('Good Morning!')"
value="In the Morning">
<input type="button"
onClick="myfunction('Good Evening!')"
value="In the Evening">
</form>
<p>
When you click on one of the buttons, a
function will be called. The function will
alert
the argument that is passed to it.
</p>
</body>
</html>
Output
myfunction (txt) receives “ Good
Morning!”
myfunction (txt) receives “ Good
Evening !”
JavaScript Objects
• JavaScript is not a true Object Oriented language as
C++ or Java but rather an Object Based language.
• Objects in JavaScript are software entities such as the
browser window or an HTML document.
JavaScript Objects (contd.)
JavaScript Objects (contd.)
JavaScript Objects (contd.)
JavaScript Objects (contd.)
JavaScript Objects (contd.)
JavaScript Objects (contd.)
JavaScript Objects (contd.)
JavaScript Objects (contd.)
JavaScript Objects (contd.)
Instances of Computer Objects
(contd.)
JavaScript Core Objects
Document Object Model
• The DOM is a programming API for documents.
• It is based on an object structure that closely resembles the
structure of the documents it models.
• For instance, consider this table, taken from an HTML
document:
<TABLE>
<TBODY>
<TR> <TD>Shady Grove</TD> <TD>Aeolian</TD> </TR>
<TR> <TD>Over the River, Charlie</TD> <TD>Dorian</TD>
</TR>
</TBODY>
</TABLE>
Graphical representation of the DOM of the example table
Document Object Model (contd.)
Document Object Model (contd.)
• With JavaScript you can restructure an entire HTML
document. You can add, remove, change, or reorder
items on a page.
• To change anything on a page, JavaScript needs
access to all elements in the HTML document. This
access, along with methods and properties to add,
move, change, or remove HTML elements, is given
through the Document Object Model (DOM).
Document Object Model (contd.)
Document Tree
How to access the nodes in an
HTML
• You can find the element you want to manipulate in
several ways:
– By using the getElementById() and
getElementsByTagName() methods
– By using the parentNode, firstChild, and lastChild
properties of an element node
Navigator Object
• Navigator object is the object representation of the
client internet browser or web navigator program that is
being used.
• This is a top level object to all others object in DOM
hierarchy.
Navigator Object Properties
• appCodeName – The name of the browser’s code
such as Internet Explorer
• appName – The name of the browser.
• appVersion – The version of the browser.
• plugins – An array of plug-ins supported by the
browser and installed on the browser.
• cpuClass – The type of CPU which may be “x86”.
• cookieEnabled – A boolean value of true or false
depending on whether cookies are enabled in the
browser.
Navigator Object Methods
• javaEnabled() – Returns a boolean telling if the
browser has JavaScript enabled.
Window Object
• The Window object is the top level object in the
JavaScript hierarchy.
• The Window object represents a browser window.
• A Window object is created automatically with every
instance of a <body> tag.
Window Object Properties
• name – sets of return the name of the window.
• statusbar - sets whether or not the browser’s statusbar
should be visible.
• toolbar - sets whether or not the browser’s toolbar
should be visible.
• document
• history
Window Object Methods
• open() – Opens a new browser window.
• createPopup() – Creates a popup window.
• setInterval(code,millisec[,lang]) – Evaluates an
expression at specified intervals.
• focus() – sets the focus to the current window.
• blur() – removes focus from the current window.
• close() – closes the current window.
Document Object
• The document object represents the entire HTML
document and can be used to access all elements in a
page.
• The document object is part of the window object and is
accessed through the window.document property or
simply document.
Document Object Collections
• anchors[] - Returns a reference to all Anchor objects in
the document.
• forms[] - Returns a reference to all Form objects in the
document.
• images[] - Returns a reference to all Image objects in
the document.
• links[] - Returns a reference to all Area and Link objects
in the document.
Document Object Properties
• Body – gives direct access to the <body> element.
• Cookie – Sets or returns all cookies associated with the
current document.
• lastModified – Returns the date and time a document
was last modified.
• Title – Returns the title of the current document.
• URL – Returns the URL of the current document.
Document Object Methods
• write() - Writes HTML expressions or JavaScript code
to a document
• getElementByID() – Returns a reference to the first
object with the specified id.
• getElementsByName() – Returns a collection of
objects with the specified name.
• getElementsByTagName() – Return a collection of
objects with the specified tag name.
History Object
• History object is a JavaScript object.
• The History object is automatically created by the
JavaScript runtime engine and consists of and array of
URLs.
• It is a part of window object & accessed through
window.history property.
History Object (contd.)
History Object (contd.)
Form Object Model
Form Object Model (contd.)
Form Object Model (contd.)
Form Object Model (contd.)
Form Object Model (contd.)
Form Object Model (contd.)
Form Object Model (contd.)
Form Object Model (contd.)
Form Object Model (contd.)
Form Object Model (contd.)
Form Object Model (contd.)
Cookies
• A cookie can store a small amount of information about
a user visiting a site.
• A cookie is a small text file that is stored on the site
visitor's computer by their browser .
• Because the cookie is stored on the user’s computer, it
does not require any server space no matter how many
users you have .
• With JavaScript, you can both create and retrieve
cookie values.
Cookies (contd.)
• You can use cookies to :
– save user preferences.
– customize data.
– remember the last visit.
– Keep track of items in an order while a user
browses.
– Remember the information your site’s visitors gave
last time.
• Cookies can be created, read and erased by
JavaScript. They are accessible through the property
document.cookie
Cookies (contd.)
• What does a cookie contain?
– Name value pair
• The first element in a cookie is a "name"
attribute, followed by the data to be stored in the
cookie.
– The expiry date
• specifies how long the cookie is valid for.
Cookies (contd.)
• What does a cookie contain?
– The path
• this states where the cookie may be accessed
from on the Web site. Most often, this is set to
the server's document root.
– The domain
• The "domain" attribute allows you to set a
domain name for the cookie. Again, this is
optional.
Format of Cookie
• First the name value pair.
• Then a semicolon and a space.
• Then the expiry date.
– Expiry date should be in UTC format.
• Then again a semicolon and a space.
• Then the path.
Format of Cookie (contd.)
• document.cookie=<name of cookie>=<value of
cookie>;<blank space>expires=<date in UTC
format>;<blank space>path=<path location>
Example
document.cookie = ‘user=Mujtaba; expires=Fri, 30 April 2021 20:47:11 UTC;
path=/'
Example of Setting a Cookie
<html>
<head>
<script language="JavaScript">
function setCookie(name, value) {
var exp=new Date(“April 30,2021")
document.cookie=name+"="+escape
(value)+"; expires="+exp.toGMTString() +"; path=/“
document.write(“Cookie has been set”)
) </script>
</head>
<body>
<form>
<input type="button"
value="Set a Cookie"
onClick="setCookie(‘user',‘
Paul Smith')">
</form>
</body>
</html>
Set an expiry date
What does the
escape function
do?
escape() function
• There's no escape!
– Strictly speaking, we should be escaping our cookie
values -- encoding non-alphanumeric characters
such as spaces and semicolons.
– This is to ensure that our browser can interpret the
values properly.
– Fortunately this is easy to do with JavaScript's
escape() function.
For example
document.cookie = "username=" + escape(“Paul
Smith") + "; expires=15/02/2003 00:00:00";
Example of Setting a Cookie
<html>
<head>
<script language="JavaScript">
function setCookie(name, value) {
var exp=new Date(“April 30,2021")
document.cookie=name+"="+escape
(value)+"; expires="+exp.toGMTString() +"; path=/“
document.write(“Cookie has been set”)
)
</script>
</head>
<body>
<form>
<input type="button" value="Set a
Cookie"
onClick="setCookie(‘user',‘Mujtaba')"
>
</form>
</body>
</html>
Setting the cookie
The value stored is
user=Mujtaba
Reading a Cookie
<html>
<head>
<script language="JavaScript">
function readCookie() {
var ca = document.cookie
document.write(ca)
}
</script>
</head>
<body>
<form><input type="button"
value="read"
onClick="readCookie()">
</form>
</body>
</html>
Returns the cookie
name value pair
Value retrieved is
user=Mujtaba
Extracting only the value from
the Cookie
<html>
<head>
<script language="JavaScript">
function readCookie(c_name)
{
if (document.cookie.length>0)
{c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
document.write(
document.cookie.substring(c_
start,c_end))
}
}
}
</script>
</head>
<body>
<form> <input type="button"
value="read"
onClick="readCookie('user')">
</form>
</body>
</html>
Displays the value:
Mujtaba
Delete Cookies
<html>
<head>
<script language="JavaScript">
function deleteCookie ( cookie_name)
{
var cookie_date = new Date ( )
cookie_date.setTime ( cookie_date.getTime() - 1 )
document.cookie = cookie_name += "=; expires=" +
cookie_date.toGMTString()
}
</script>
</head>
<body>
<form>
<input type="button"
value=“delete"
onClick="deleteCookie(‘
user')">
</form>
</body>
</html>
The cookie's expiry date is set
to one second less then the
current date.
Modifying a cookie
• To modify a cookie simply reset the values and use the
same procedure for setting the cookie.
• Ensure that the cookie name is existing or a new
cookie will be created.

Contenu connexe

Tendances

Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
Chamnap Chhorn
 

Tendances (20)

Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Introduction To JavaScript
Introduction To JavaScriptIntroduction To JavaScript
Introduction To JavaScript
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
Javascript
JavascriptJavascript
Javascript
 

Similaire à Lecture 5 javascript

Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
22x026
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
SANTOSH RATH
 

Similaire à Lecture 5 javascript (20)

Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
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
Java scriptJava script
Java script
 
WTA-MODULE-4.pptx
WTA-MODULE-4.pptxWTA-MODULE-4.pptx
WTA-MODULE-4.pptx
 
Java script basics
Java script basicsJava script basics
Java script basics
 
FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
Java script
Java scriptJava script
Java script
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
 
Web Technology Part 2
Web Technology Part 2Web Technology Part 2
Web Technology Part 2
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Java script
Java scriptJava script
Java script
 

Dernier

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Dernier (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

Lecture 5 javascript

  • 2. Objectives • Introduction to JavaScript – Introduction to JavaScript programming language – Using Script tag – Inserting Java Script into tags – Linking Java Script from separate files • JavaScript expression and Operators – Defining and naming variables – Data Types – Expression – Operators – Arithmetic, String, Logical, Assignment, typeof
  • 3. Objectives (Contd.) • Functions and Flow Control – Flow Control • If…else • For loops • while loops • Break and continue statements – Using JavaScript functions • Built in functions • User defined functions • Returning values from functions • Events, Event Handlers
  • 4. Objectives (Contd.) • Objects and Arrays – Properties and Methods – Browser Object Hierarchy – Addressing Objects – Creating Objects – Objects and Variables – External Objects – Security Implications – Arrays and Objects
  • 5. Objectives (Contd.) • Document Object Model – Introduction to DOM – The Navigator Object – The Window Object – Communicating between windows – Working With Frames in the DOM – The Document object – The Location & History Object – Image Object – Link Object
  • 6. Objectives (Contd.) • Form Validation The Form Object Model – Recap of Form Elements – Form Tag Events – Controlling Submission – Forms as Navigation – List Events – Buttons – Text Processing
  • 7. Objectives (Contd.) • Cookies – Introduction to HTTP Cookies – Formatting Cookies – Persisting Cookies – Cookie Security – JavaScript & Cookies – Reading / Writing Cookies – Modifying and deleting Cookies
  • 8. Introduction to Java Scripts • What is JavaScript??? – JavaScript is a scripting Language created by Netscape What is a Scripting Language??? •Scripting Language is a lightweight programming language. • Scripting Languages are not needed to be compiled. •The language is interpreted at runtime.
  • 9. Introduction to JavaScript (Contd.) – A JavaScript is usually directly embedded in an HTML page. – External JavaScripts can be created which can be used by HTML pages. – JavaScript adds interactivity to HTML pages. – JavaScript's are integrated into the browsing environment.
  • 10. Introduction to JavaScript (Contd.) Is JavaScript same as Java??? • Java is a programming language which requires compilation and interpretation. • Java is used to make large scale applications. • JavaScript is a scripting language which just requires interpretation. The script is some set of commands which the browser interprets. • JavaScript is used to add interactivity in HTML Pages.
  • 11. Types of JavaScript • Client-Side JavaScript (CSJS) -- an extended version of JavaScript that enables the enhancement and manipulation of web pages and client browsers. • Server-Side JavaScript (SSJS) -- an extended version of JavaScript that enables back-end access to databases, file systems, and servers. • Core JavaScript -- the base JavaScript language.
  • 12. Core JavaScript • Core JavaScript encompasses all of the statements, operators, objects, and functions that make up the basic JavaScript language. • The following objects are part of core JavaScript: – array – date – math – number – string
  • 13. Client Side Java Scripting • CSJS is composed of core JavaScript and many additional objects, such as the following: – document – form – frame – window – Navigator – History
  • 14. Server Side JavaScript • SSJS is composed of core JavaScript and additional objects and functions for accessing databases and file systems, sending e-mail, and so on.
  • 15. Uses of JavaScript (Client Side) • Menus for Navigation • Form Validation • Popup Windows • Password Protecting • Math Functions • Special effects with document and background • Status bar manipulation • Messages • Mouse Cursor Effects • Links
  • 16. Syntax rules of JavaScript • Statements may or may not contain a semicolon at the end. • Multiple statements on one line must be separated by a semicolon. • JavaScript is case sensitive.
  • 17. Using <script> tag • The HTML <script> tag is used to enter JavaScript into a HTML. • The <script> tag can be embedded within – <head> tag. – <body> tag. • JavaScript in the head section will be executed when called. • JavaScript in the body section will be executed while the HTML page is loaded. • Unlimited number of JavaScript’s can be placed both in head and body section in a HTML document.
  • 18. Using <script> tag Eg: <html> <head><title>Example</title> </head> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html> Is a standard command for writing output to a page
  • 19. How to Handle Older Browsers • Browsers that do not support JavaScript will display the script as it is. Use the HTML comment tag to prevent this. Eg. <script type="text/javascript"> <!-- document.write("Hello World!") // --> </script> The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line.
  • 20. Using an External JavaScript • A JavaScript can be written in an external file, which can be used by different HTML pages. • The external script cannot contain the <script> tag. • The external file needs to end with the .js extension.
  • 21. Using External JavaScript (contd.) document.write("This line has been writen in the External JavaScript!!!") External.js <html> <head><title>Example</title> </head> <body> <script src="External.js"> </script>> <p > This line has been written in the html page!!! </p> </body> </html> JavaScript.html
  • 22. JavaScript Variables and expression • JavaScript Variables – Variable: • A variable is a symbolic name that represents some data in the memory. • A variable value can change during the execution of the JavaScript. • A variable can be referred by its name to see or change its value. • Variables are name are case sensitive. • Must begin with a letter or underscore.
  • 23. Rules of a Variable • Variable Declaration – Variables can be declared using the var statement var <variable name>=some value – Variables can also be created without using var statement <variable name>=some value – Eg var firstname=“Samuel” OR firstname=“Samuel”
  • 24. Data Type in JavaScript • JavaScript is a loosely typed language. • Data Type of Variable need not be specified during declaration. • Data types are automatically converted during script execution. Loosely Typed??
  • 25. Data Type in JavaScript (contd.) • JavaScript recognizes the following type of values: Values string numbers null boolean 9, 3.56 true or false Samuel, ”Samuel J Palmisano” A Special keyword which refers to nothing
  • 26. Data Type in JavaScript (contd.)
  • 34. Flow Control • Conditional Statements – if statement - use this statement if you want to execute some code only if a specified condition is true. – if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false. – if...else if....else statement - use this statement if you want to select one of many blocks of code to be executed. – switch statement - use this statement if you want to select one of many blocks of code to be executed.
  • 36. break and continue Statements • There are two special statements that can be used inside loops: – break. – continue. • Break – The break command will break the loop and continue executing the code that follows after the loop (if any). • Continue – The continue command will break the current loop and continue with the next value.
  • 37. Example of break statement <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=5;i++) { if (i==3){break} document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 1 The number is 2
  • 38. Example of continue statement <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=5;i++) { if (i==3){continue} document.write("The number is " + i) document.write("<br />") } </script> </body> </html> Result The number is 0 The number is 1 The number is 2 The number is 4 The number is 5
  • 40. Functions • A function is a reusable piece of code that will be executed when called for. • A function can be called from anywhere from within the page or even from other pages if the function is stored in an external JavaScript (.js) file. • Functions can be embedded in the <head></head> and within the<body> </body> tag.
  • 41. Predefined functions in JavaScript • DialogBoxes – alert( message) Displays an alert box with a message defined by the string message. Eg. alert(“An Error Occurred!”)
  • 42. Predefined functions in JavaScript (contd.) • confirm(message) – When called, it will display the message and two boxes. One box is "OK" and the other is "Cancel". If OK is selected, a value of true is returned, otherwise a value of false is returned. Eg. confirm(“Do you wish to Continue?”)
  • 43. Predefined functions in JavaScript (contd.) • prompt(message) – Displays a box with the message passed to the function displayed. – The user can then enter text in the prompt field, and choose OK or Cancel. – If the user chooses Cancel, a NULL value is returned. If the user chooses OK, the string value entered in the field is returned. Eg: prompt(“enter your Name”)
  • 44. Predefined functions in JavaScript (contd.) • Conversion Functions – eval(string) Converts a string to an integer or a float value. Eg x=“20” y=eval(x)+10 y contains the value 30
  • 45. Predefined functions in JavaScript (contd.) – isNaN(value) If the value passed is not a number then a boolean value of true is returned else the boolean value of false is returned. Eg x=“Samuel” y=isNaN(x) The value stored in y is true
  • 46. Predefined functions in JavaScript (contd.) – parseInt(string) Converts a string to an integer returning the first integer encountered which is contained in the string. Eg x=77AB67 y=parseInt(x) y stores the value 77
  • 47. Predefined functions in JavaScript (contd.) – parseFloat(string) Converts a string to an float value . Eg x=77.5AB67 y=parseFloat(x) y stores the value 77.5
  • 54. Common Event Handlers (contd.) • onLoad and onUnload – The onload and onUnload events are triggered when the user enters or leaves the page. – The onload event is also triggered when the image is loaded. The showstatus() function will be called when a user enters a page <body onload=“showStatus()”>
  • 55. Common Event Handlers (contd.) • onFocus, onBlur and onChange – The onFocus, onBlur and onChange events are often used in combination with validation of form fields. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()">;
  • 56. Common Event Handlers (contd.) • onSubmit – The onSubmit event is used to validate ALL form fields before submitting it. The checkForm() function will be called when the user clicks the submit button in the form. <form method="post" action="xxx.htm" onsubmit="return checkForm()">
  • 57. Common Event Handlers (contd.) • onMouseOver and onMouseOut – onMouseOver and onMouseOut are often used to create "animated" buttons. An alert box appears when an onMouseOver event is detected: <a href="http://www.ibm.com" onmouseover="alert('An onMouseOver event’)”> <img src=“ibmlogo.gif" width="100" height="30"> </a>
  • 64. Example (contd.) function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 } <Input type=“text” name=“text3” value=“”>
  • 65. Example (contd.) function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 } <INPUT TYPE=“button” value=“ +op “ onClick=“Addition(text1.value,text2.value)”>
  • 66. Example (contd.) FaaDoOEngineers.com function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 if(Ans==temp){ alert(“Your Result agrees with JavaScript!”) document.form1.text1.value=‘’ document.form1.text2.value=‘’ document.form1.text3.value=‘’ } else{ alert(“No, JavaScript evalutes this operation differently”) document.form1.text3.value=‘’ }} <Form name=“form1” Method=“post” action=“url” onSubmit=“return validate()> <Input type=“text” name=“text1” value=“”>
  • 67. A Complete Program <html> <head> <script type="text/javascript"> function myfunction(txt) { alert(txt) } </script> </head> <body> <form> <input type="button" onClick="myfunction('Good Morning!')" value="In the Morning"> <input type="button" onClick="myfunction('Good Evening!')" value="In the Evening"> </form> <p> When you click on one of the buttons, a function will be called. The function will alert the argument that is passed to it. </p> </body> </html>
  • 69. myfunction (txt) receives “ Good Morning!”
  • 70. myfunction (txt) receives “ Good Evening !”
  • 71. JavaScript Objects • JavaScript is not a true Object Oriented language as C++ or Java but rather an Object Based language. • Objects in JavaScript are software entities such as the browser window or an HTML document.
  • 81. Instances of Computer Objects (contd.)
  • 83. Document Object Model • The DOM is a programming API for documents. • It is based on an object structure that closely resembles the structure of the documents it models. • For instance, consider this table, taken from an HTML document: <TABLE> <TBODY> <TR> <TD>Shady Grove</TD> <TD>Aeolian</TD> </TR> <TR> <TD>Over the River, Charlie</TD> <TD>Dorian</TD> </TR> </TBODY> </TABLE>
  • 84. Graphical representation of the DOM of the example table Document Object Model (contd.)
  • 85. Document Object Model (contd.) • With JavaScript you can restructure an entire HTML document. You can add, remove, change, or reorder items on a page. • To change anything on a page, JavaScript needs access to all elements in the HTML document. This access, along with methods and properties to add, move, change, or remove HTML elements, is given through the Document Object Model (DOM).
  • 86. Document Object Model (contd.) Document Tree
  • 87. How to access the nodes in an HTML • You can find the element you want to manipulate in several ways: – By using the getElementById() and getElementsByTagName() methods – By using the parentNode, firstChild, and lastChild properties of an element node
  • 88. Navigator Object • Navigator object is the object representation of the client internet browser or web navigator program that is being used. • This is a top level object to all others object in DOM hierarchy.
  • 89. Navigator Object Properties • appCodeName – The name of the browser’s code such as Internet Explorer • appName – The name of the browser. • appVersion – The version of the browser. • plugins – An array of plug-ins supported by the browser and installed on the browser. • cpuClass – The type of CPU which may be “x86”. • cookieEnabled – A boolean value of true or false depending on whether cookies are enabled in the browser.
  • 90. Navigator Object Methods • javaEnabled() – Returns a boolean telling if the browser has JavaScript enabled.
  • 91. Window Object • The Window object is the top level object in the JavaScript hierarchy. • The Window object represents a browser window. • A Window object is created automatically with every instance of a <body> tag.
  • 92. Window Object Properties • name – sets of return the name of the window. • statusbar - sets whether or not the browser’s statusbar should be visible. • toolbar - sets whether or not the browser’s toolbar should be visible. • document • history
  • 93. Window Object Methods • open() – Opens a new browser window. • createPopup() – Creates a popup window. • setInterval(code,millisec[,lang]) – Evaluates an expression at specified intervals. • focus() – sets the focus to the current window. • blur() – removes focus from the current window. • close() – closes the current window.
  • 94. Document Object • The document object represents the entire HTML document and can be used to access all elements in a page. • The document object is part of the window object and is accessed through the window.document property or simply document.
  • 95. Document Object Collections • anchors[] - Returns a reference to all Anchor objects in the document. • forms[] - Returns a reference to all Form objects in the document. • images[] - Returns a reference to all Image objects in the document. • links[] - Returns a reference to all Area and Link objects in the document.
  • 96. Document Object Properties • Body – gives direct access to the <body> element. • Cookie – Sets or returns all cookies associated with the current document. • lastModified – Returns the date and time a document was last modified. • Title – Returns the title of the current document. • URL – Returns the URL of the current document.
  • 97. Document Object Methods • write() - Writes HTML expressions or JavaScript code to a document • getElementByID() – Returns a reference to the first object with the specified id. • getElementsByName() – Returns a collection of objects with the specified name. • getElementsByTagName() – Return a collection of objects with the specified tag name.
  • 98. History Object • History object is a JavaScript object. • The History object is automatically created by the JavaScript runtime engine and consists of and array of URLs. • It is a part of window object & accessed through window.history property.
  • 102. Form Object Model (contd.)
  • 103. Form Object Model (contd.)
  • 104. Form Object Model (contd.)
  • 105. Form Object Model (contd.)
  • 106. Form Object Model (contd.)
  • 107. Form Object Model (contd.)
  • 108. Form Object Model (contd.)
  • 109. Form Object Model (contd.)
  • 110. Form Object Model (contd.)
  • 111. Form Object Model (contd.)
  • 112. Cookies • A cookie can store a small amount of information about a user visiting a site. • A cookie is a small text file that is stored on the site visitor's computer by their browser . • Because the cookie is stored on the user’s computer, it does not require any server space no matter how many users you have . • With JavaScript, you can both create and retrieve cookie values.
  • 113. Cookies (contd.) • You can use cookies to : – save user preferences. – customize data. – remember the last visit. – Keep track of items in an order while a user browses. – Remember the information your site’s visitors gave last time. • Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie
  • 114. Cookies (contd.) • What does a cookie contain? – Name value pair • The first element in a cookie is a "name" attribute, followed by the data to be stored in the cookie. – The expiry date • specifies how long the cookie is valid for.
  • 115. Cookies (contd.) • What does a cookie contain? – The path • this states where the cookie may be accessed from on the Web site. Most often, this is set to the server's document root. – The domain • The "domain" attribute allows you to set a domain name for the cookie. Again, this is optional.
  • 116. Format of Cookie • First the name value pair. • Then a semicolon and a space. • Then the expiry date. – Expiry date should be in UTC format. • Then again a semicolon and a space. • Then the path.
  • 117. Format of Cookie (contd.) • document.cookie=<name of cookie>=<value of cookie>;<blank space>expires=<date in UTC format>;<blank space>path=<path location> Example document.cookie = ‘user=Mujtaba; expires=Fri, 30 April 2021 20:47:11 UTC; path=/'
  • 118. Example of Setting a Cookie <html> <head> <script language="JavaScript"> function setCookie(name, value) { var exp=new Date(“April 30,2021") document.cookie=name+"="+escape (value)+"; expires="+exp.toGMTString() +"; path=/“ document.write(“Cookie has been set”) ) </script> </head> <body> <form> <input type="button" value="Set a Cookie" onClick="setCookie(‘user',‘ Paul Smith')"> </form> </body> </html> Set an expiry date What does the escape function do?
  • 119. escape() function • There's no escape! – Strictly speaking, we should be escaping our cookie values -- encoding non-alphanumeric characters such as spaces and semicolons. – This is to ensure that our browser can interpret the values properly. – Fortunately this is easy to do with JavaScript's escape() function. For example document.cookie = "username=" + escape(“Paul Smith") + "; expires=15/02/2003 00:00:00";
  • 120. Example of Setting a Cookie <html> <head> <script language="JavaScript"> function setCookie(name, value) { var exp=new Date(“April 30,2021") document.cookie=name+"="+escape (value)+"; expires="+exp.toGMTString() +"; path=/“ document.write(“Cookie has been set”) ) </script> </head> <body> <form> <input type="button" value="Set a Cookie" onClick="setCookie(‘user',‘Mujtaba')" > </form> </body> </html> Setting the cookie The value stored is user=Mujtaba
  • 121. Reading a Cookie <html> <head> <script language="JavaScript"> function readCookie() { var ca = document.cookie document.write(ca) } </script> </head> <body> <form><input type="button" value="read" onClick="readCookie()"> </form> </body> </html> Returns the cookie name value pair Value retrieved is user=Mujtaba
  • 122. Extracting only the value from the Cookie <html> <head> <script language="JavaScript"> function readCookie(c_name) { if (document.cookie.length>0) {c_start=document.cookie.indexOf(c_name + "=") if (c_start!=-1) { c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start) if (c_end==-1) c_end=document.cookie.length document.write( document.cookie.substring(c_ start,c_end)) } } } </script> </head> <body> <form> <input type="button" value="read" onClick="readCookie('user')"> </form> </body> </html> Displays the value: Mujtaba
  • 123. Delete Cookies <html> <head> <script language="JavaScript"> function deleteCookie ( cookie_name) { var cookie_date = new Date ( ) cookie_date.setTime ( cookie_date.getTime() - 1 ) document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString() } </script> </head> <body> <form> <input type="button" value=“delete" onClick="deleteCookie(‘ user')"> </form> </body> </html> The cookie's expiry date is set to one second less then the current date.
  • 124. Modifying a cookie • To modify a cookie simply reset the values and use the same procedure for setting the cookie. • Ensure that the cookie name is existing or a new cookie will be created.