0 ratings0% found this document useful (0 votes) 135 views22 pagesClient Side Programming (Javascript)
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
CHAPTER
CLIENT SIDE PROGRAMMING
(JAVASCRIPT)
10.0 INTRODUCTION
Javascript can be thought of as an extension to HTML,
which allows authors to incorporate some sanctionality in
their web pages. So, now, whenever the user presses the
‘SUBMIT button, you don’t necessarily have to invoke a cgi
script to do the processing. If it is something simple, you
can do the processing locally using Java script and give
back the results. Java script can also be used in a number
of ways to spice up your web page.
+ Itis a cross-platform scripting language developed
by Netscape.
+ Itcan be used for both client side and server side
applications.
+ Client-side Javascript is typically executed in a
browser that supports the language.
+ Itis an interpreted object based language that can
be included in HTML page.
+ You can access a number of elements in your
HTML page and manipulate them using Java script.
+ Helps in the creation of HTML pages capable of
responding to user events like mouse clicks, key
presses, selection of elements in the form.
Java Scripts is a scripting language that reflects the
object orientation of web pages. HTML documents that
include Java script can react to visitor actions, process and
check information that visitor provide, and even deliver
na0
VYYVYYYYYYYYYY
vyy
Inside this Chapter
Introduction
What is JavaScript?
What can a JavaScript Do?
Introduction to java Script Syntax
Variables
Statements in Java Script
Using Operations in Java Script
JavaScript Popup Boxes
JavaScript Functions
JavaScript Loops
Events and Event Handling
JavaScript-Catching Errors
Insert Special Characters
Object Model in Java Script
(Object Oriented Programming)
The HTML DOM
Browser Detection
Form Handling (Processing
Forms Using Hidden Fields)
JavaScript Animation
JavaScript Timing Events
Miscellaneous Topics
@ scanned with OKEN Scanner© appropriate to each visitor, For example, you can use Java script to change a buttons
1@ Mouse cursor moves over it.
10.1 WHAT IS JAVASCRIPT?
+ JavaScript was de
ned to add interactivity to HTML pages.
Pane
+ A JavaScript consists oflines of executable computer | both concept and design! Java
code (developed by Sun Microsystems)
+ A JavaScripts usually embedded directly into HTML |S a powerful and much more
pages ‘complex programming language ~
+ JavaScripts an interpreted language (means that [nthe same cetogon/ a5 Cand Cr,
sctpts execute wihnout pratiinary compilation)
+ Everyone can use JavaScript without purchasing a license.
10.2 WHAT CAN A JAVASCRIPT DO?
+ JavaScript gives HTML designers a programming tool- HTML authors are normally not
programmers, bl JavaScripts a scripting language with avery simple syntax! Almost anyone
‘can put small "snippets" of fo their HTML pages
can put dynamic text into an HTML page - A JavaScript statement lke this:
docu + name + "") can write a variable text into an HTML page
+ JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML element
‘can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
‘can be used to validate data -A JavaScript can be used to validate form data
submitted to a server. This saves the server from extra processing
er - A JavaScript can be used to
W's browser, and - depending on the browser-load another page specifically
designed for that browser
+ JavaScript can be used to create cookies -A JavaScript can be used to store and retrieve
information on the visitors computer,
10.3 INTRODUCTION TO JAVA SCRIPT SYNTAX
Now we will see how a javascript code is put into html page
cheml>
ebody>
escript type="text /Javascript*>
document .write|
‘The code above will produce this output on an HTML page:
Hello World!
Example Explained
‘Toinserta JavaScriptinto an HTML page, we use the tells where
the JavaScript stars and ends:
‘The two forward slashes at he end of comment ine (I) are a JavaScript comment symbol, This
prevents JavaScript from executing the line,
Where to Put
JavaSer pts in a page wi
not always what we want. Sor
when a user triggers an event.
Scripts in the head section: Scripts to be executed when they are called, or when an events
xecuted immadiately while the page loads nto the browser. This is
imes we want to execute a script when a page loads, other
coon et epee agg
‘Scripts in the body section: Scripts tobe executed when the page loads go inthe body section.
When you place a script in the body section it generates the content of the,
eheml>
cecript type="text /Javascript">
‘Scripts in both the body and the head section: You can place an unlimited numberof srpts
in your document, so you can have scrips in both the body andthe head section.
ehtml>
FEF nectenatsootmetcannte epog
‘Touse the external script, point tothe js fein the “src attribute of he
the specified condition is true.
@ scanned with OKEN Scannerwe
Wiob Development
10.5.2 If...else Statement
{recut some code a contion Is tue and another code the condition is not
ise statement,
Af (condition)
{
code to be executed if condition ie true
}
else
{
code to be executed if condition is not true
}
Example
10.5.3 If...else if...else Statement
‘You should use the if..lseif..e'se statement if you want to select one of many sets of lines to
execute.
Syntax
Af (condition)
code to be executed if condition! is true
.
chet ste Pepannig Unga
}
fe if (condition)
{
code to be executed if condition? is true
)
elee
{
code to be executed if condition! and
‘condition? are not true
)
Example
cecript types"text/javascript">
var d = new Date()
var time » d.gettioure()
4 (timecio)
{
docunent.write(* Good morning to all B.TECH studente of UPTUI")
}
else if (tine>t0 G& timeci6)
{
document write (*cb> Good morning to all NCA students of UPTUI")
}
else
{
document .write("*)
)
10.5.4 The JavaScript Switch Statement
‘You should use the Switch statement if you want o select one of many blocks of code to be
executed
‘Syntax
ewitch (a)
{
case 1:
‘execute code block 2
break
case 2:
@ scanned with OKEN ScannerEEE ETS UN IORI
execute code block 2
break
default
code to be executed if n is
different from case 1 and 2
}
Thisis how't works: First we have a single expression n (most often a variable), thats evaluated
‘once. The value ofthe expressionis then com the values foreach case inthe struct
there isa match, the black of code assaciated with that case is executed. Use break to prevent the
‘code from running into the next case automa
Example
cocript types*text/javaseript">
//¥ou will receive a different greeting based
/Jon what day it is, Note that Sunday=0,
/IMonday=1, Tuesday=2, etc.
var denew Date()
theDay=d.getDay ()
switeh (theDay)
{
case 5:
document.write ("Finally Friday")
break
case 6
document .weite ("Super Saturday")
break
case 0:
document.write ("Sleepy Sunday")
break
default
docunent .write(*I'm looking forward to this weekend!*)
}
10.6 USING OPERATIONS IN JAVA SCRIPT wimp)
Operators injava script are same a in all programming languages. These operators are categorized
in different categories as below:
(Chen oie Programming \avascnpt) ~~
10.6.1 Arithmetic Operators
Operator | Descrinton Example | Result)
+ | Addition x2 rl
ye
wy
= ‘Subtraction = 3
ye
xy
atipication 75 20
1
xy
7 | Bion 155 3
52 25
% | Modulus avision remainder) | 512 7
1018 2
102 o
| inerement x5 16 |
== Decrement x5 xed |
10.6.2 Assigament Operators
Operator | Example | ls TheSameAs
= sy =
= ey ey
= ay ey
= xy ay
[__ ay ealy
* wey rey
10.6.8 Comparison Operators
‘Operator | Beseription Example
=| wequalto Seb umstake
is equal to (checks for both value and type)
is not equal
is greater than
S>Bretunsfalse |
@ scanned with OKEN Scanner58 retums tue
‘5528 rotum:
558 retuns tue
10.6.4 Logical Ope
Operator [Description | Example
cr ‘nd 8
3
(<1088y> 1) etums te
Hl 8
==5 || y==5) retums false
Hi nat
3
Hay) retums true
text, for example "Hello World”. To stick two or mare sting variables
extsetxeaeexta
“The variable tet now containe “What averynice day". Toadd.a space between to string variables,
insert a space into the expression, OR in one ofthe strings.
extiethhat a very"
exta="nice day!"
extactxeLey sate
extaetWhat a very *
extzetnice day!*
extantae Lote?
“The variable txt3 now contains ‘What avery nice day!
10.6.6 Conditional Operator
‘JavaScript also contains a conditional operator that assigns.a value toa variable based on some
condition.
Syntax
variablename= (condition) ?valuel :value2
‘lent Side Programming (Javaseph) age
_AO7 JAVASCRIPT POPUP BOXES
10.7.1 Alert Box.
Analertboxis ote used ifyou want toma
‘an alert box pops up, the User wil ave to cick
‘Syntax:
alert ("eonetext*)
10.7.2 Confirm Box
pronpt ("sonetext*, “defaultvalus")
10.8 JAVASCRIPT FUNCTIONS
inan extemal js
document. How
could be wise to
Example
eneml>
ehead>
hits the button. We have added an onClick event to the button that will execute the function
displaymessage() when the button s clicked.
10.8.1 Function
Syntax:
The syntax for creating a function Is:
function functionnane (varl, var2, ...,varX)
code
}
var', var2, etc are variables or values passed into the function. The {and the ) defines the start
and end of the function.
‘A function with no parameters must include the parentheses ()
after the function name:
Do not forget about the importance of capitals in JavaScripl The |;
word function must be writen in lowercase letters, otherwise
JavaScript enor occurs! Also note that you must call afuncton with
ihe exact same capitals as in the function name. |
10.8.2 The Return Statement
‘The retum statement is used to specify the value thatis returned from the function. So, functions
that are going to retun a value must use the return statement,
Example
The function below should return the product of two numbers (a and b):
function prod(a,b)
(
wath
return x
)
‘When you call the function above, you must pass along two parameters:
Product sprod(2, 3)
‘The returned value from the prodt) function is 6, and it will be stored in the variable called
rodiit.
10.9 JAVASCRIPT LOOPS (temp)
‘Very often when you write code, you want the same block of code torun over and over again in a row.
Instead of adding several almost equal lines ina script we can use laops to perform a task lke this.
In JavaScript there are two different kinds of oops:
+ for = oops through a block of code a specified number of
+ while -loops trough a block of code while a specified condition is tue
10.9.1 The for Loop
‘The forloop is used when you know in advance how many times the script should run,
Syntax
for (varestartvalue;vare-endvalue;var=var+increnent)
{
code to be executed
)
Example
Explanation: The example below defines a loop that stats with =0. The loop will continue to run
‘slong as iis less than, or equal to 10. wil increase by 1 each time the loop runs.
‘The increment parameter could also be negative, and the <= could be any comparing statement
chtml>
eecript types"text/Javacript">
@ scanned with OKEN Scannerfor (is0;4cn10;i44)
‘ )
Socument.write(*The number is © + 4)
document write ("