Professional Documents
Culture Documents
Day 2
2007 IBM Corporation
JavaScript
2007 IBM Corporation
Objectives
Introduction to JavaScript
Introduction to JavaScript programming language Using Script tag Inserting Java Script into tags Linking Java Script from separate files
Objectives (Contd.)
Objectives (Contd.)
Objectives (Contd.)
Objectives (Contd.)
Objectives (Contd.)
Cookies
Introduction to HTTP Cookies Formatting Cookies Persisting Cookies Cookie Security JavaScript & Cookies Reading / Writing Cookies Modifying and deleting Cookies
Introduction To JavaScript
2007 IBM Corporation
What is JavaScript???
JavaScript is a scripting Language created by Netscape Scripting Language is a lightweight programming language. Scripting Languages are not needed to be compiled. The language is interpreted at runtime.
10
11
JavaScript is a scripting
language which just requires interpretation. The script is some set of commands which the browser interprets.
Types of JavaScript
13
Core JavaScript
number
string
14
15
16
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
17
Client Side JavaScript ________________ is an extended version of JavaScript that enables the enhancement and manipulation of web pages and client browsers Server Side JavaScript Core JavaScript
18
Client Side JavaScript ________________ is an extended version of JavaScript that enables the enhancement and manipulation of web pages and client browsers Server Side JavaScript Core JavaScript
19
20
JavaScript in the head section will be executed when called. JavaScript in the body section will be executed while the HTML
page is loaded.
21
<body>
<script type="text/javascript"> document.write("Hello World!") </script> </body> </html>
Is a standard command for writing output to a page
22
document.write("Hello World!")
// --> </script>
23
The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line.
2007 IBM Corporation
The external script cannot contain the <script> tag. The external file needs to end with the .js extension.
24
<script></script is embedded
within <body></body>
26
<script></script is embedded
within <body></body>
27
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.
29
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
30
31
numbers string
9, 3.56
boolean
true or false
null
A Special keyword which refers to nothing
32
33
JavaScript Operators
Operators
Arithmetic
Assignment
Conditional String
Comparison
Logical
typeof
34
35
36
37
38
39
40
41
number
string null
42
number
string null
43
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.
45
while statement
46
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.
47
Result
48
Result The number is 0 The number is 1 The number is 2 The number is 4 The number is 5
49
For loop
50
Functions
51
52
53
Eg:
prompt(enter your Name)
54
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
55
56
x=77AB67
y=parseInt(x) y stores the value 77
57
58
59
60
61
Events
62
Events (contd.)
63
Event Handlers
64
65
66
The showstatus() function will be called when a user enters a page <body onload=showStatus()>
67
The checkEmail() function will be called whenever the user changes the content of the field:
68
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()">
69
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>
70
71
72
Example
73
Example (contd.)
74
Example (contd.)
75
Example (contd.)
76
Example (contd.)
77
Example (contd.)
78
Example (contd.)
function Addition(x,y)
{
var x1=document.form1.text1.value var y1=document.form1.text2.value var Ans=document.form1.text3.value var temp=x1+y1 }
79
Example (contd.)
function Addition (x,y) { var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value
var temp=x1+y1
}
80
Example (contd.)
function Addition (x,y) {
var x1=parseInt(x) var y1=parseInt(y) var Ans=document.form1.text3.value var temp=x1+y1 }
81
Example (contd.)
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= }}
82
83
84
A Complete Program
<html>
<input type="button"
<head>
<script type="text/javascript"> function myfunction(txt) {
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>
alert(txt)
} </script> </head> <body> <form>
85
Output
86
87
88
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.
90
91
92
93
94
95
96
97
98
99
100
101
Boolean
Math
1.
2. 3. 4.
Boolean
Date Function Math Date Number
5.
6.
Number
String
Function
String
102
Boolean
Math
1.
2. 3. 4.
Boolean
Date Function Math Date Number
5.
6.
Number
String
Function
String
103
104
105
106
107
108
Boolean
Math
1.
2. 3. 4.
Boolean
Date Function Math Date Number
5.
6.
Number
String
Function
String
109
110
111
112
113
114
115
116
117
118
119
120
121
Boolean
Math
1.
2. 3. 4.
Boolean
Date Function Math Date Number
5.
6.
Number
String
Function
String
122
123
124
125
126
Boolean
Math
1.
2. 3. 4.
Boolean
Date Function Math Date Number
5.
6.
Number
String
Function
String
127
128
129
130
131
132
Boolean
Math
1.
2. 3. 4.
Boolean
Date Function Math Date Number
5.
6.
Number
String
Function
String
133
134
135
136
Boolean
Math
1.
2. 3. 4.
Boolean
Date Function Math Date Number
5.
6.
Number
String
Function
String
137
138
s1 = "2 + 2
eval(s1) eval(s2) eval(s2.valueOf());
139
140
Defining Arrays
An Array object is used to store a set of values in a single variable name.
An Array object is created with the new keyword. An array can be created as: var MyArray=new Array() An array can also be created by specifying the array size. var MyArray=new Array(3)
141
Arrays (contd.)
Data can be entered into an array as:
var MyArray=new Array() MyArray[0]=Paul MyArray[1]=Sam MyArray[2]=Niel Data can also be entered into an array as: var MyArray=new Array(Paul,Sam, Niel)
142
Arrays (contd.)
Accessing Arrays
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0 .
143
</TBODY>
</TABLE>
145
146
All browsers have implemented this recommendation, and therefore, incompatibility problems in the DOM have almost disappeared.
147
Document Tree
148
149
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.
150
151
152
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> or <frameset> tag.
153
154
Frame Object
Frame object represents an HTML frame.
For each instance of a <frame> tag in an HTML document, a Frame object is created.
157
In
Document Object Model Frames are instances of Window object
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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.
177
178
179
Location Object
Location object is an JavaScript object it is not an DOM object.
The Location object is automatically created by the JavaScript runtime engine and contains information about the current URL. The Location object is part of the Window object and is accessed through the window.location property.
181
182
183
184
185
186
187
188
190
191
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.
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
Cookies
2007 IBM Corporation
Cookies
224
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 sites visitors gave last time.
225
Cookies (contd.)
226
Cookies (contd.)
The domain
The "domain" attribute allows you to set a domain name for the cookie. Again, this is optional.
227
Question
The name-value pair is the
_____________ element in the Cookie second third
first
228
Answer
The name-value pair is the
_____________ element in the Cookie second third
first
229
230
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.
231
document.cookie=<name of cookie>=<value of
cookie>;<blank space>expires=<date in UTC format>;<blank space>path=<path location>
Example
232
</script>
</head> <body>
var exp=new Date("January 31,2008") <form> <input type="button" value="Set document.cookie=name+"="+escape a Cookie" (value)+"; expires="+exp.toGMTString() onClick="setCookie(user',Paul +"; path=/ Smith')"> document.write(Cookie has been set) </form>
</body>
</html>
Set an expiry date
233
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";
234
</head>
<body> <form> <input type="button" value="Set a Cookie" onClick="setCookie(user',Paul Smith')"> </form> </body> </html>
document.cookie=name+"="+escape
(value)+"; expires="+exp.toGMTString() +"; path=/ document.write(Cookie has been set) )
The value stored is user=Paul Smith
235
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> Value retrieved is user=Paul Smith
</html>
Returns the cookie name value pair
236
{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
237
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() }
<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.
</script>
</head>
238
Modifying a cookie
239
Summary
Cookies are small text files that sit on your hard disk. Cookies are created when you visit websites that use cookies to
store information that they need (or prefer).
Websites often use cookies to personalize the user experience such as remembering your name (assuming you supplied it previously) or remembering the items in your shopping cart from previous visits. they are quite harmless.
Despite the many misconceptions about cookies being malicious, Cookies can't give your personal details to other websites, or
transmit a virus or anything like that.
A cookie can only be read by the server that created it. Websites normally use cookies to make its users' lives easier, not
harder.
240