You are on page 1of 22
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 Scanner we 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 Scanner EEE 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 Scanner 58 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 Scanner for (is0;4cn10;i44) ‘ ) Socument.write(*The number is © + 4) document write ("
Result ‘The number is 0 ‘The number is 1 ‘The number is 2 ‘The nunber is 3 ‘The nunber is 4 ‘The number ie 5 ‘The number is 6 ‘The nusber ie 7 ‘The nunber is 6 ‘The number is 9 ‘The number is 10 10.9.2 The whi ‘The while loop is used when you want the loop to execute and continue executing while the specified condition is a while (varesendvalue) { code to be executed } ws FE ec conten ono ctr Example ‘Explanation: The example below d ‘as tong as iis less than, or equal to 1 sloop that stars with =0. The loop will continue torun increase by 1 each time the loop runs. _ ebody> joript type="text /Javas code to be executed } while (varceendvalue) Example ‘cocript typesttext/javascript"> var is0 0 @ scanned with OKEN Scanner while (i<0) Result The number is 0 10.9.4 JavaScript Break and Continue Statements ‘There are two special statements that can be used inside loops: break and continue Break ‘The break command will break the loop and continue executing the code that follows after the oop (it any). Example ental» var ino for (is0;ice10;i++) ( Sf (i203) (break) docunent .write(*The number is * + i) document .write(*
") } Result ‘The nunber is 0 The number is 1 The nunber is 2 Continue The continue command wil break the current oop and continue with the next valve. Example ehtml> ” e/a > Result The musber ie 0 ‘The number is 1 ‘The nusber ie 2 The nuiber ie 4 The nunber is 5 ‘The number is 6 ‘The nunber is 7 The nunber is 8 The nunber is 9 ‘The nunber is 10 10.9.5 JavaScript For...1n Statement ‘The for..n statement is used to loop (iterate) through the elements of an array or through the properties of an object. The code in the body ofthe fr... in loop is executed once for each element property Syntax for (variable in object) { | gode to be executed oy “The variable argument can be a named variable, an aay element, or a property of an object. Example Using for..in to loop through an array: @ scanned with OKEN Scanner var exter" function message () { cry { adddlert (*Welcome guest!*) } cateh(err) { txt="There was an error on this page.\n\n" txtes"Error description: * + err.description + *\n\n" txte="Click OK to continue. \n\n" alert (txt) ) ) ‘ Example 2 ‘The next example uses a confirm box to display a custom message teling users they can cick OK to continue viewing the page or click Cancel to gotothe homepage. ithe confrm method retumns false, the user cicked Cancel, and the code redirects the user. the conf method returns tue, the ‘code does nothing: var texte" function message () { ey { adddiert ("Welcome guest") J catch (err) { txt="There was an error on thie page.\n\n" txtvaMClick OK to continue viewing this page, \n" txtes"or Cancel to return to the hone page.\n\n" A€ (Ieonfirm(txt)) { @ scanned with OKEN Scanner —ee—ae———ee document .location.href=*url" ) ) . First you will earn how to use the throw statement to create an exception. The throw statement ‘can be used together withthe ty..catch statement. ‘The Throw Statement “The throw statement allows you to create an exception. Ifyou use this statement together with the try..catch statement, you can control program flow and generate acourate error messages. Syntax throw (exception) “The exception can bea sting, integer, Boolean or an object. Note that throwis writen in lowercase letters. Using uppercase letters will generate a JavaScript error! Example 1 “The example below determines the value ofa variable called x. the value of xis higher than 10 “orlower than O we are going o throw an error, The error is then caught by the catch argument and the proper error message is displayed escript type="text/javascript"> var xeprompt ("Enter a number between 0 and 10:", try ™ Af Go10) throw "Erri" else if(x<0) throw "Err2" ) cateh (er) { if (ere="Brr2") alert ("Error! The value is too high") if(er == "Err2") alert ("Error! The value is too low") ) ‘The onerror Event ‘We have ust explained how to use the try..catch statement to catch errors ina web page \we are going to explain how to use the onerror event for the same purpase. The oneror eve whenever thre isa script erorin the page. To use the onerror event, you must create handle the errs. Then you cal ithandler. The event hand called with three arguments: m 1 page that caused te error (the line where the eror occ Syntax @ scanned with OKEN Scanner onerrorshandlezrr finction handleBrr (msg, url, 1) { / [Handle the error here return true or false The value returned by onerror determines whether the brow: standard error message. If you retumn false, the brow standard error message in the JavaScript consol true, the browser does not display the standard error Example ‘The following example shows how to catch the error with the onerror event chead> cbody> 10.12 INSERT SPECIAL CHARACTERS ‘The backslash () is used to insert apostrophes, new lines, quotes, and other special characters into a text string. Look at the folowing JavaScript code: | var txteWe are the so-called "Vikings" from the north.* document.write (txt) JavaScript, a string is started and stopped with either single or double quotes. This means that ing above will be chopped to: We are the so-called. To solve this problem, you must place a lash (\) before each double quote in "Viking". This tums each double quote into string literal var txtetile are the so-called \*Vikings\* from the north." document .write (txt) JavasScript will now output the proper tex string: We are the so-called "Vikings" from the north Hore is another example: document.write ("You \& me a: ‘The example above will produce the f You & me are singing! ‘The table below lists other special characters that can be added toa text sting withthe backslash sign Code Outputs ¥ single quote r doutle quote co ampersand) [x backslash (Chont Side Programming (Javascript) mS eariage rum | backspace ¥ ‘orm feed JavaScript is Case Sensitive ‘A function named “myfunetion”is not the same as “myFunction* and a variable isnot the same as "myvar’. JavaScripts case sensitive - therefore watch your capil ‘when you create o call variables, objects and functions, White Space JavaScript ignores extra spaces. You can add white space to your script to make tmore readable, ‘The following nes are equivalent: nnane="itege" zane = "Hege* Break up a Code Line You can bresk up a code line within a text string witha backslash The example below willbe displayed propery: Aocunent ,write(*Hello \ Worlai") However, you cannot break up a code ne like this: document.write \ ("Hello Worta!") Comments ‘You can edd comments to your sciptby using to stashes I: [}ehis is a comment document .weite( "Hello World!*) ‘or by using and */ (his creates a mltsine comment block} [1 This is a comment block. Tt contains several lines */ document .write ("Hello World!") 10.13 OBJECT MODEL IN JAVA SCRIPT (OBJECT ORIENTED PROGRAMMING) JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. We (Wetemp) @ scanned with OKEN Scanner 316 ee ee 10.13.1 Properties tes ae the values asocte whan length property of tring object ‘the 7 inthe S8CHIpE type="text javascripts var txtettelio wortais document.write (exe length) var str="iello worla!* document.write (str.toUppercase()) — ‘The output ofthe code above will be: HELLO WORLD! 10.13.3 String object The String object is used to manipulate a stored piece of text. Examples of use: ‘The following example uses the length property of the String object to find the length ofa sting? var txte"Hello world! document .write (txt .length) ‘The code above will result inthe following output: var txte"Hello world!" document .write (txt. toUpperCase()} ‘The code above will result in the folowing output: HELLO WORLD! 10.13.3.1 Defining Dates To Date object i used fo work wih datos and times. We define a Date object with the now xarpword, The following codeine defines a Dae object called myDate: va py Denke revpDLt) Cie SeePoxanningoasegy S|, ae myantornew Date utomaticaly hold the curent date and time 10.19.3.2 Manipulate Dates \We can easily manipulate the date by using the methods available for the Date object. In the ‘example below we seta Date object toa specific date (14th January 2010} var myDatesnew Date myDate, setFull¥ear (2010, 0,14) ‘And inthe following example we set a Date object to be 5 days into the future var myDatesnew Date() —~ myDate. setDate (myDate.getDate() +5) H ading five days to a date shifts the month or year, the changes. are handled automatically bythe Date object itself 10.13.3.3 Comparing Dates The Date objects also used to compare two dates. The following example compares todays ‘ate with the 14th January 2010: var myDatesnew Date() nyDate. setFullYear (2610, 0,14) var today + new Date() if (mybatestéday) alert ("Today is ‘before 14th January 2020") else alert (*Today ie after 14th ganuary 2010") 10.18.4 Defining Arrays (imp) The Aray objects used osore soto values ina single vaste nam] We deine an Aray object ceyword. The following code line defines an Array Objet called myArray var myArrayenew Array() ‘There are two ways of adding values to an aay (you can add as many values as you need to define as many variables you require). @ scanned with OKEN Scanner var mycarsenew Array("Saab", same) "volvo", you specify numbers or ruerfalse values inside the array then}! the type of variables will be numeric or Boolean instead of sting element in an array by referring to the name of the array and the rts at0. The following code line: Saab 10.13.4.2 Modify Values in Exi ify a value in an e ing Arrays ay, just add a new value tothe array with a specified index umber: mycar: opel” Now, the following code line: document .write (mycars [0] ) result in the following output: _- opel 10.13.5 Boolean Object The Boolean object is an object wrapper for a Boolean vale The Boolean 0 ‘Do YOU KNOW! If the Boolean object ‘value or if itis 0, -0, n is Used 16 convert a.fion-Boolean olean value (rue or false). We define a Boolean var nyBooleansnew Boolean) ‘Allthe folowing lines of code create Boolean objects with an var myBooleansnew Bool var nyBoolean-new Bool var mySooleansnew Bool ‘And al the folowing lines of code cxeate Boolean objects with an iil value of tue ‘var syBooleanenew Boclean (true) ‘var nyBocleanenew Boolean ("true") ‘var ayBooleancnew Boolean ("false") var myBoolean=new Boolean ("Richard") 10.13.6 Math Object ‘The Math object allows you to perform common mathematical tasks) {The Math object includes several mathematical values nd funesons You do notneed to define the Math cbject before using it 10.13.6.1 Mathematical Values hat can be accessed from the Math natura log of 2, natura log of 10, base Math.2 Math. Pr Math. SoRT2 Math. SgRTI_2 Math.LN2 ath. Lio Math.L0c2E Math. 100108 10.13.6.2 Mathematical Methods alues that can be accessed from the Math abject there are als: Inadditon to the mathemat ‘several functions (method Examples of functions (methoe ‘The following example uses the round{) method of the Math object to round a number to th nearest integer: docunent .write (Math. round(4.7)) ‘The code above will resultin the following output: @ scanned with OKEN Scanner se Web Development The following example uses the ra between oan andom() method of the Math object to retumn a random number document.write (Math. random()) The code above can result in the following output 0.3584516492037386 The following example uses the floor) and im je tendons rae xamole uses the foo’) and random) methods ofthe Math objec to tun a document .write (Math, floor (Math. random()*1) ) ‘The code above can result in the following output 6 10.13.7 More JavaScript Objects Folow the irks to eam more aboutthe abject and te clots, popes, meboss and events Object Description Window “The top level object in te JavaScript Rorarchy. The Window objec represents @ browser window. A Window objects created automaticaly with every instanceof a or tag ot Side Progam y (nt Side Programming (Javascript) "2. Pn Object Description | Are | Represents an cavea> aera nde an age-map [Base Ropressris a se> oemanh 7 Bow Represers be element i Baton Represents a buon alana | Event Reprecers a sae ofan event Form Represents aco eerart | Frame Represents a trame> element i Framesst Represents a arate ena ame Represents an element image Represnts an element Input bation Represents a buton nan HTL Form | Tnputchecktox | Represent a chesoxin an HTML form tnput fle presents a lepioad n an HTML form Input hidden Represents aiden fold an HTL form | Inputpassword | _ Represers a pasonod flsn an TUL orm 1 Input radio Represents aco butonin an HTL frm Represents a eset Button nan HTRL form Navigator “Contains information about he cents browser ‘Screen Conlin information about ‘deplay seen History | _ Contains the visted URLS inthe browser window | Represents a element Represenis a aable> element TableData | _ Represents a element — TableRow | _Represanis a a> elemont Textarea | _ Represents a