You are on page 1of 131

JavaScriptJavaScriptVenkatTheScriptingLanguageoftheWebvenkatshiva.reddy@gmail.co mJavaScriptJavaScriptVenkatTheScriptingLanguageoftheWebvenkatshiva.reddy@gmail.

c om

NeedforScripting HTML Merelyamark-uplanguage. CreatesClient-SideUserInterface. CannothandleClient-Sideactivitiestorespondtoauser. ThustheadventofScriptingLanguages. JavaScriptVenkatLanguages. ToMakeHTMLdocumentdynamicscriptingwasintroduced PopularScriptingLanguages Perl,REXX,J avaScript,VBScript,Tcl/TkNeedforScripting HTML Merelyamark-uplanguage. CreatesClient-SideUserInterface. CannothandleClient-Sideactivitiestorespondtoauser. ThustheadventofScriptingLanguages. JavaScriptVenkatLanguages. ToMakeHTMLdocumentdynamicscriptingwasintroduced PopularScriptingLanguages Perl,REXX,J avaScript,VBScript,Tcl/Tk

The History of JavaScript JavaScript developed by Netscape in 1995 as a method validating forms and providing interactive content to HTML. European Computer Manufacturers Association (ECMA) came to help and put forward ECMAScript which is now JavaScript Venkat an ISO Standard. At the time, Microsoft and Netscape introduced their v4 browsers which lead to the unholiness referred to as DHTML.

JavaScript Characteristics JavaScript syntax similar to C or Pascal JavaScript is Event-Driven JavaScript is platform-independent JavaScript enables quick JavaScript Venkat development JavaScript is easy to learn and use.

What is JavaScript? JavaScriptisthescriptinglanguageoftheWeb! JavaScriptisusedinmillionsofWebpagestoimprovethedesign,validateforms,detectthevis itor'sbrowser,create/usecookies,andmuchmore. WhatisJavaScript? JavaScriptisthescriptinglanguageoftheWeb! JavaScriptisusedinmillionsofWebpagestoimprovethedesign,validateforms,detectthevis itor'sbrowser,create/usecookies,andmuchmore. JavaScriptVenkat JavaScriptwasdevelopedbyNetscapeandisthemostpopularscriptinglangu ageontheinternet. JavaScriptissupportedbyallmajorbrowsers,likeNetscapeandInternetExplorer

WhatisJavaScript? JavaScriptwasdesignedtoaddinteractivitytoHTMLpages JavaScriptisascriptinglanguage(a scriptinglanguageisalightweightprogramminglanguage) AJavaScriptconsistsoflinesofexecutablecomputercode AJSitillbdddditlitHTMLJavaScript Venkat AJavaScriptisusuallyembeddeddirectlyintoHTMLpages JavaScriptisaninterpretedla nguage(meansthatscriptsexecutewithoutpreliminarycompilation) EveryonecanuseJavaScriptwithoutpurchasingalicenseWhatisJavaScript? JavaScriptwasdesignedtoaddinteractivitytoHTMLpages JavaScriptisascriptinglanguage(a scriptinglanguageisalightweightprogramminglanguage) AJavaScriptconsistsoflinesofexecutablecomputercode AJSitillbdddditlitHTMLJavaScript Venkat AJavaScriptisusuallyembeddeddirectlyintoHTMLpages JavaScriptisaninterpretedla nguage(meansthatscriptsexecutewithoutpreliminarycompilation) EveryonecanuseJavaScriptwithoutpurchasingalicense

Are Java and JavaScript the Same? NO! Java and JavaScript are two completely different languages in both concept and design! Java (developed by Sun Microsystems) JavaScript Venkat is a powerful and much more complex programming language - in the same category as C and C++.

What can a JavaScript Do? JavaScript gives HTML designers a programming tool HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into JavaScript Venkat their HTML pages

What can a JavaScript Do? JavaScript can put dynamic text into an HTML page A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript Venkat

What can a JavaScript Do? 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 JavaScript Venkat

What can a JavaScript Do? JavaScript can read and write HTML elements A JavaScript can read and change the content of an HTML element JavaScript Venkat

What can a JavaScript Do? JavaScript can be used to validate data A JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing JavaScript Venkat

What can a JavaScript Do? JavaScript can be used to detect the visitor's browser A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript Venkat

What can a JavaScript Do? JavaScript can be used to create cookies A JavaScript can be used to store and retrieve information on the visitor's computer JavaScript Venkat

JavaScript How To ? The HTML <script> tag is used to insert a JavaScript into an HTML page. <html> <body> JavaScript Venkat <script type="text/javascript"> document.write("Hello World!"); </script> </body> </html>

Ending Statements With a Semicolon (;) With traditional programming languages, like C, C++ and Java, each code statement has to end with a semicolon (;). Many programmers continue this habit when writing JavaScript, but in JavaScript Venkat general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line.

How to Handle Older Browsers? Browsers that do not support JavaScript will display the script as page content. To prevent them from doing this, we may use the HTML comment tag: <script type="text/javascript"> <! document.write("Hello World!"); JavaScript Venkat The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This prevents the JavaScript compiler from compiling the line. //--> </script>

JavaScript Where To ? JavaScriptsinthebodysectionwillbeexecutedWHILEthepageloads. JavaScriptsintheheadsectionwillbeexecutedwhenCALLED. JavaScriptVenkatJavaScriptWhereTo ? JavaScriptsinthebodysectionwillbeexecutedWHILEthepageloads. JavaScriptsintheheadsectionwillbeexecutedwhenCALLED. JavaScriptVenkat

Scripts in the head section Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it. <html> JavaScript Venkat <head> <script type="text/javascript"> .... </script> </head>

Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page. <html> <head> JavaScript Venkat </head> <body> <script type="text/javascript"> .... </script> </body>

Scripts in both the body and head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section. <html> <head> <script type="text/javascript"> .... JavaScript Venkat </script> </head> <body> <script type="text/javascript"> .... </script> </body>

Using an External JavaScript file Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page. To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension. JavaScript Venkat Note: The external script cannot contain the <script> tag! To use the external script, point to the .js file in the "src" attribute of the <script> tag: Ex: <script src="xxx.js"></script>

JavaScript Lexical Structure Keywords They have a special meaning in JavaScript. Part of the language syntax itself. Also called as Reserved Words. JavaScript Venkat break case continue default delete do else export for function if import in new return switch this typeof var void while with

Operators in JavaScript Assignment = Arithmetic + -* / % Logical && || ! Comparison == != < <= > >= Compound Assign * JavaScriptVenkatCompound Assignment += -= *= /= %= String + (for concatenation) Increment & Decrement ++ -Typeof operator Used to identify the type of variable OperatorsinJavaScriptAssignment = Arithmetic + -* / % Logical && || ! Comparison == != < <= > >= Compound Assign * JavaScriptVenkatCompound Assignment += -= *= /= %= String + (for concatenation) Increment & Decrement ++ -Typeof operator Used to identify the type of variable

OperatorPrecedencePrecedence Operator 1 Parenthesis or array subscript 2 !, -, ++, -3 * / % 4+ JavaScriptVenkat5 <<=>>= 6==!= 7 && 8 || 9 ?: 10 = += -= *= /= %= OperatorPrecedencePrecedence Operator 1 Parenthesis or array subscript 2 !, -, ++, -3 * / % 4+ JavaScriptVenkat5 <<=>>= 6==!= 7 && 8 || 9 ?: 10 = += -= *= /= %=

JavaScriptGuidelines SomeimportantthingstoknowwhenscriptingwithJavaScript. JavaScriptVenkatJavaScriptGuidelines SomeimportantthingstoknowwhenscriptingwithJav aScript. JavaScriptVenkat

JavaScript is Case Sensitive A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the same as "myvar". JavaScript is case sensitive - therefore watch your capitalization closely when JavaScript Venkat you create or call variables, objects and functions.

Symbols Openingsymbols,like({["',mustalwayshaveamatchingclosingsymbol,like'"]}). JavaScriptVenkatSymbols Openingsymbols,like({["',mustalwayshaveamatchingclosingsym bol,like'"]}). JavaScriptVenkat

WhiteSpace JavaScriptignoresextraspaces.Youcanaddwhitespacetoyourscripttomakeitmor ereadable.Thefollowinglinesareequivalent: JavaScriptVenkat name= Venkat name = Venkat" WhiteSpace JavaScriptignoresextraspaces.Youcanaddwhitespacetoyourscripttomakeitmor ereadable.Thefollowinglinesareequivalent: JavaScriptVenkat name= Venkat name = Venkat"

BreakupaCodeLine Youcanbreakupacodelinewithinatextstringwithabackslash.Theexampleb elowwillbedisplayedproperly: document.write("Hello\ World!") JavaScriptVenkat However,youcannotbreakupacodelinelikethis: document.write\ ("HelloWorld!") Theexampleabovewillgenerateanerror! BreakupaCodeLine Youcanbreakupacodelinewithinatextstringwithabackslash.Theexampleb elowwillbedisplayedproperly: document.write("Hello\ World!") JavaScriptVenkat However,youcannotbreakupacodelinelikethis: document.write\ ("HelloWorld!") Theexampleabovewillgenerateanerror!

InsertSpecialCharacters Youcanalsoinsertspecialcharacters(like"';&)withabackslash: document.write ("You \& I sing \"Happy \ Birthday\".") JavaScriptVenkaty ) Theexampleabovewillproducethisoutput: You & I sing "Happy Birthday". InsertSpecialCharacters Youcanalsoinsertspecialcharacters(like"';&)withabackslash: document.write ("You \& I sing \"Happy \ Birthday\".") JavaScriptVenkaty ) Theexampleabovewillproducethisoutput: You & I sing "Happy Birthday".

Comments Startacommentwithtwoslashes"//": sum=a + b //this is a comment Using/*and*/tocreateamulti-linecomment: JavaScriptVenkatcomment: /* This is a comment block. It contains several lines */ Comments Startacommentwithtwoslashes"//": sum=a + b //this is a comment Using/*and*/tocreateamulti-linecomment: JavaScriptVenkatcomment: /* This is a comment block. It contains several lines */

JavaScriptVariables Avariableisa"container"forinformationyouwanttostore.Avariable' svaluecanchangeduringthescript.Youcanrefertoavariablebynametoseeitsvalueortochan geitsvalue. Rulesforvariablenames: ViblitiJavaScriptVenkatVariablenamesarecasesensitive Theymustbeginwithaletterorthe underscorecharacter Cannotbeakeyword IMPORTANT!JavaScriptiscase-sensitive!Avariablen amedstrnameisnotthesameasavariablenamedSTRNAME! JavaScriptVariables Avariableisa"container"forinformationyouwanttostore.Avariable' svaluecanchangeduringthescript.Youcanrefertoavariablebynametoseeitsvalueortochan geitsvalue. Rulesforvariablenames: ViblitiJavaScriptVenkatVariablenamesarecasesensitive Theymustbeginwithaletterorthe underscorecharacter Cannotbeakeyword IMPORTANT!JavaScriptiscase-sensitive!Avariablen amedstrnameisnotthesameasavariablenamedSTRNAME!

DeclareaVariable Youcancreateavariablewiththevarstatement: var strname = some value Youcanalsocreateavariablewithoutthevarstatement: JavaScriptVenkat strname = some value DeclareaVariable Youcancreateavariablewiththevarstatement: var strname = some value Youcanalsocreateavariablewithoutthevarstatement: JavaScriptVenkat strname = some value

Assign a Value to a Variable You can assign a value to a variable like this: var strname = venkat" Or like this: strname = venkat" The variable name is on the left side of JavaScript Venkat the expression and the value you want to assign to the variable is on the right. Now the variable "strname" has the value venkat".

JavaScript Venkat recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed. JavaScriptVenkatrecognizedonlybythefunctioninwhichitisdeclared. Ifyoudeclareavariableoutsideafunction, allthefunctionsonyourpagecanaccessit. Thelifetimeofthesevariablesstartswhentheyaredeclared,andendswhenthepageisclosed. LifetimeofVariables Whenyoudeclareavariablewithinafunction,thevariablecanonlybeacc essedwithinthatfunction.Whenyouexitthefunction,thevariableisdestroyed.Thesevaria blesarecalledlocalvariables.Youcanhavelocalvariableswiththesamenameindifferentfu nctions,becauseeachis,

Variables-Example<html> <body> <scripttype="text/javascript"><scripttype="text/javascript"><scripttype="text/ja vascript"><scripttype="text/javascript"> varname= Venkat"varname= Venkat"varname= Venkat"varname= Venkat" document.write(name)document.write(name)document.write(name)document.write(name) document.write("<h1>"+name+"</h1>")document.write("<h1>"+name+"</h1>")document.w rite("<h1>"+name+"</h1>")document.write("<h1>"+name+"</h1>") </script></script></script></script> JavaScriptVenkat<p>Thisexampledeclaresavariable, assignsavaluetoit, andthendisplaysthevariable.</p> <p>Thenthevariableisdisplayedonemoretime,onlythistimeasaheading.</p> </body> </html> Variables-Example<html> <body> <scripttype="text/javascript"><scripttype="text/javascript"><scripttype="text/ja vascript"><scripttype="text/javascript"> varname= Venkat"varname= Venkat"varname= Venkat"varname= Venkat" document.write(name)document.write(name)document.write(name)document.write(name) document.write("<h1>"+name+"</h1>")document.write("<h1>"+name+"</h1>")document.w rite("<h1>"+name+"</h1>")document.write("<h1>"+name+"</h1>") </script></script></script></script> JavaScriptVenkat<p>Thisexampledeclaresavariable, assignsavaluetoit, andthendisplaysthevariable.</p> <p>Thenthevariableisdisplayedonemoretime,onlythistimeasaheading.</p> </body> </html>

ConditionalStatements Veryoftenwhenyouwritecode,youwanttoperformdifferentactionsfo rdifferentdecisions.Youcanuseconditionalstatementsinyourcodetodothis. InJavaScriptwehavethefollowingconditionalstatements: JavaScriptVenkat ifstatement if...elsestatement if...elseif....elsestatement switchstate mentConditionalStatements Veryoftenwhenyouwritecode,youwanttoperformdifferentactio nsfordifferentdecisions.Youcanuseconditionalstatementsinyourcodetodothis. InJavaScriptwehavethefollowingconditionalstatements: JavaScriptVenkat ifstatement if...elsestatement if...elseif....elsestatement switchstate ment

ConditionalStatements ifstatement-usethisstatementifyouwanttoexecutesomecodeonlyif aspecifiedconditionistrue if...elsestatement-usethisstatementifyouwanttoexecutesom ecodeiftheconditionistrueandanothercodeiftheconditionisfalseJavaScriptVenkatcond itionisfale if...elseif....elsestatement-usethisstatementifyouwanttoselectoneofman yblocksofcodetobeexecuted switchstatement-usethisstatementifyouwanttoselectoneofma nyblocksofcodetobeexecutedConditionalStatements ifstatement-usethisstatementifyouw anttoexecutesomecodeonlyifaspecifiedconditionistrue if...elsestatement-usethisstat ementifyouwanttoexecutesomecodeiftheconditionistrueandanothercodeiftheconditioni sfalseJavaScriptVenkatconditionisfale if...elseif....elsestatement-usethisstatemen tifyouwanttoselectoneofmanyblocksofcodetobeexecuted switchstatement-usethisstateme ntifyouwanttoselectoneofmanyblocksofcodetobeexecuted

IfStatement Youshouldusetheifstatementifyouwanttoexecutesomecodeonlyifaspecifiedco nditionistrue. Syntaxif(if(if(if(conditionconditionconditioncondition)))) {{{{ JavaScriptVenkat{{{{ codetobeexecutedifconditionistruecodetobeexecutedifconditionistruecodetobeexecut edifconditionistruecodetobeexecutedifconditionitrue}}}} Notethatifiswritteninlowercaseletters. Usinguppercaseletters(IF)willgenerateaJavaScripterror! IfStatement Youshouldusetheifstatementifyouwanttoexecutesomecodeonlyifaspecifiedco nditionistrue. Syntaxif(if(if(if(conditionconditionconditioncondition)))) {{{{ JavaScriptVenkat{{{{ codetobeexecutedifconditionistruecodetobeexecutedifconditionistruecodetobeexecut edifconditionistruecodetobeexecutedifconditionitrue}}}} Notethatifiswritteninlowercaseletters. Usinguppercaseletters(IF)willgenerateaJavaScripterror!

IfStatement Example1<scripttype="text/javascript"> //Writea"Goodmorning"greetingif//thetimeislessthan10vard=newDate() vartime=d.getHours() JavaScriptVenkatif(time<10) { document.write("<b>Goodmorning</b>") } </script> IfStatement Example1<scripttype="text/javascript"> //Writea"Goodmorning"greetingif//thetimeislessthan10vard=newDate() vartime=d.getHours() JavaScriptVenkatif(time<10) { document.write("<b>Goodmorning</b>") } </script>

IfStatement Example2<scripttype="text/javascript"> //Write"Lunch-time!"ifthetimeis11vard=newDate() vartime=d.getHours() if(time==13) JavaScriptVenkat{ document.write("<b>Lunch-time!</b>") } </script> IfStatement Example2<scripttype="text/javascript"> //Write"Lunch-time!"ifthetimeis11vard=newDate() vartime=d.getHours() if(time==13) JavaScriptVenkat{ document.write("<b>Lunch-time!</b>") } </script>

If...elseStatement Ifyouwanttoexecutesomecodeifaconditionistrueandanothercodeifthe conditionisnottrue,usetheif....elsestatement. if(condition) JavaScriptVenkat{ codetobeexecutedifconditionistrue} else{ codetobeexecutedifconditionisnottrue} If...elseStatement Ifyouwanttoexecutesomecodeifaconditionistrueandanothercodeifthe conditionisnottrue,usetheif....elsestatement. if(condition) JavaScriptVenkat{ codetobeexecutedifconditionistrue} else{ codetobeexecutedifconditionisnottrue}

If...else Statement : Example <script type="text/javascript"> // If the time is less than 10, you will get a // "Good morning" greeting. // Otherwise you will get a "Good day" greeting. var d = new Date() var time = d.getHours() JavaScript Venkat if (time < 10){ document.write("Good morning!") } else { document.write("Good day!") } </script>

If...else if...else Statement Youshouldusetheif....elseif...elsestatementifyouwanttoselectoneofmanysetsoflinest oexecute. if (condition1) { code to be executed if condition1 is true } else if (condition2) JavaScriptVenkat( ) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not tr} If...elseif...elseStatement Youshouldusetheif....elseif...elsestatementifyouwantto selectoneofmanysetsoflinestoexecute. if (condition1) { code to be executed if condition1 is true } else if (condition2) JavaScriptVenkat( ) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not tr} u

If...else if...else Statement : Example <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time<10) { document.write("<b>Good morning</b>") } JavaScript Venkat else if (time>10 && time<16) { document.write("<b>Good day</b>") } else { document.write("<b>Hello World!</b>") } </script>

The JavaScript Switch Statement You should use the switch statement if you want to select one of many blocks of code to be executed. switch(n) { case 1: execute code block 1 break JavaScript Venkat case 2: execute code block 2 break default: code to be executed if n is different from case 1 and 2 }

switch(n) case : How it works? This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, JavaScript Venkat the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

switch(n) case : Example <script type="text/javascript"> // You will receive a different greeting based on what day it is. // Note that Sunday=0, Monday=1, Tuesday=2, etc. var d=new Date() theDay=d.getDay() switch (theDay) { JavaScript Venkat case 5: document.write("Finally Friday"); break case 6: document.write("Super Saturday"); break case 0: document.write("Sleepy Sunday"); break default: document.write("I'm looking forward to this weekend!") } </script>

JavaScript Loops LoopsinJavaScriptareusedtoexecutethesameblockofcodeaspecifiednumberoftimesorwhile aspecifiedconditionistrue. JavaScriptVenkatJavaScriptLoops LoopsinJavaScriptareusedtoexecutethesameblockofcod easpecifiednumberoftimesorwhileaspecifiedconditionistrue. JavaScriptVenkat

JavaScriptLoops Veryoftenwhenyouwritecode,youwantthesameblockofcodetorunoverandove ragaininarow.Insteadofaddingseveralalmostequallinesinascriptwecanuseloopstoperfo rmatasklikethis. JavaScriptLoops Veryoftenwhenyouwritecode,youwantthesameblockofcodetorunoverandove ragaininarow.Insteadofaddingseveralalmostequallinesinascriptwecanuseloopstoperfo rmatasklikethis. JavaScriptVenkat InJavaScriptthereistwodifferentkindofloops: for-loopsthroughablockofcodeaspecifiednumberoftimes while-loopsthroughablockofcodew hileaspecifiedconditionistrue

TheforLoop Theforloopisusedwhenyouknowinadvancehowmanytimesthescriptshouldrun. SyntaxJavaScriptVenkatfor(var=startvalue;var<=endvalue;var=var+increment) { codetobeexecuted} TheforLoop Theforloopisusedwhenyouknowinadvancehowmanytimesthescriptshouldrun. SyntaxJavaScriptVenkatfor(var=startvalue;var<=endvalue;var=var+increment) { codetobeexecuted}

TheforLoop:Example Explanation:Theexamplebelowdefinesaloopthatstartswithi=0. Theloopwillcontinuetorunaslongasiislessthan,orequalto10.iwillincreaseby1eachtime theloopruns. Note:Theincrementparametercouldalsobenegative,andthe<= couldbeanycomparingstatement. <html> <body> <script type="text/javascript"> JavaScriptVenkatvar i=0 for (i=0;i<=10;i++) { document.write("The no. is " + i + "<br> )} </script> </body> </html> TheforLoop:Example Explanation:Theexamplebelowdefinesaloopthatstartswithi=0. Theloopwillcontinuetorunaslongasiislessthan,orequalto10.iwillincreaseby1eachtime theloopruns. Note:Theincrementparametercouldalsobenegative,andthe<= couldbeanycomparingstatement. <html> <body> <script type="text/javascript"> JavaScriptVenkatvar i=0 for (i=0;i<=10;i++) { document.write("The no. is " + i + "<br> )} </script> </body> </html>

Thewhileloop Thewhileloopisusedwhenyouwantthelooptoexecuteandcontinueexecutingwhil ethespecifiedconditionistrue. while(var<=endvalue) { JavaScriptVenkat{ codetobeexecuted} Note:The<=couldbeanycomparingstatement. Thewhileloop Thewhileloopisusedwhenyouwantthelooptoexecuteandcontinueexecutingwhil ethespecifiedconditionistrue. while(var<=endvalue) { JavaScriptVenkat{ codetobeexecuted} Note:The<=couldbeanycomparingstatement.

Thewhileloop:Example Explanation:Theexamplebelowdefinesaloopthatstartswithi=0.Thel oopwillcontinuetorunaslongasiislessthan,orequalto10.iwillincreaseby1eachtimethel oopruns. <html> <body> <script type="text/javascript"> var i=0 while (i<=10) JavaScriptVenkatwhile (i<=10) { document.write("The no. is " + i + "<br>") i=i+1 } </script> </body> </html> Thewhileloop:Example Explanation:Theexamplebelowdefinesaloopthatstartswithi=0.Thel oopwillcontinuetorunaslongasiislessthan,orequalto10.iwillincreaseby1eachtimethel oopruns. <html> <body> <script type="text/javascript"> var i=0 while (i<=10) JavaScriptVenkatwhile (i<=10) { document.write("The no. is " + i + "<br>") i=i+1 } </script> </body> </html>

Thedo...whileLoop Thedo...whileloopisavariantofthewhileloop.Thisloopwillalwaysexec uteablockofcodeONCE,andthenitwillrepeattheloopaslongasthespecifiedconditionistru e. Thisloopwillalwaysbeexecutedonce,eveniftheconditionisfalse,becausethecodeareexec utedbeforetheconditionistested. JavaScriptVenkatdo{ codetobeexecuted}while(var<=endvalue) Thedo...whileLoop Thedo...whileloopisavariantofthewhileloop.Thisloopwillalwaysexec uteablockofcodeONCE,andthenitwillrepeattheloopaslongasthespecifiedconditionistru e. Thisloopwillalwaysbeexecutedonce,eveniftheconditionisfalse,becausethecodeareexec utedbeforetheconditionistested. JavaScriptVenkatdo{ codetobeexecuted}while(var<=endvalue)

The do...while Loop: Example <html> <body> <script type="text/javascript"> var i=0 do { JavaScript Venkat document.write("The no is " + i + "<br>") i++ } while (i<0) </script> </body> </html>

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 loop (if any). JavaScript Venkat Continue The continue command will break the current loop and continue with the next value.

break Statement : Example <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { JavaScript Venkat if (i==3){break} document.write("The no. is " + i + "<br") } </script> </body> </html>

continue Statement : Example <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3){continue} JavaScript Venkat document.write("The no is " + i + "<br>") } </script> </table> </body> </html>

JavaScript Popup Boxes InJavaScriptwecancreatethreekindofpopupboxes: Alertbox, Confirmbox, Promptbox. JavaScriptVenkatJavaScriptPopupBoxes InJavaScriptwecancreatethreekindofpopupboxes: Alertbox, Confirmbox, Promptbox. JavaScriptVenkat

AlertBox Analertboxisoftenusedifyouwanttomakesureinformationcomesthroughtotheuser. Whenanalertboxpopsup,theuserJavaScriptVenkatwillhavetoclick"OK"toproceed. Syntax: alert("sometext") AlertBox Analertboxisoftenusedifyouwanttomakesureinformationcomesthroughtotheuser. Whenanalertboxpopsup,theuserJavaScriptVenkatwillhavetoclick"OK"toproceed. Syntax: alert("sometext")

ConfirmBox Aconfirmboxisoftenusedifyouwanttheusertoverifyoracceptsomething. Whenaconfirmboxpopsup,theuserwillhavetoclickeither"OK"or"Cancel"toproceed. JavaScriptVenkatproceed. Iftheuserclicks"OK",theboxreturnstrue. Iftheuserclicks"Cancel",theboxreturnsfalse. Syntax: confirm("sometext") ConfirmBox Aconfirmboxisoftenusedifyouwanttheusertoverifyoracceptsomething. Whenaconfirmboxpopsup,theuserwillhavetoclickeither"OK"or"Cancel"toproceed. JavaScriptVenkatproceed. Iftheuserclicks"OK",theboxreturnstrue. Iftheuserclicks"Cancel",theboxreturnsfalse. Syntax: confirm("sometext")

PromptBox Apromptboxisoftenusedifyouwanttheusertoinputavaluebeforeenteringapage. Whenapromptboxpopsup,theuserwillhavetoclickeither"OK"or"Cancel"toproceedafterente ringaninputvalue. JavaScriptVenkatproceedafterenteringaninputvalue. Iftheuserclicks"OK"theboxreturnstheinputvalue.Iftheuserclicks"Cancel"theboxreturn snull. Syntax: prompt("sometext","defaultvalue") PromptBox Apromptboxisoftenusedifyouwanttheusertoinputavaluebeforeenteringapage. Whenapromptboxpopsup,theuserwillhavetoclickeither"OK"or"Cancel"toproceedafterente ringaninputvalue. JavaScriptVenkatproceedafterenteringaninputvalue. Iftheuserclicks"OK"theboxreturnstheinputvalue.Iftheuserclicks"Cancel"theboxreturn snull. Syntax: prompt("sometext","defaultvalue")

JavaScriptFunctions Afunctionisareusablecode-blockthatwillbeexecutedbyanevent,orwh enthefunctioniscalled. JavaScriptVenkatfunctionfunctionName([args]) { statementstoexecute [return(value)] } JavaScriptFunctions Afunctionisareusablecode-blockthatwillbeexecutedbyanevent,orwh enthefunctioniscalled. JavaScriptVenkatfunctionfunctionName([args]) { statementstoexecute [return(value)] }

JavaScript Functions: Why? To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function. A function contains some code that will be executed only by an event or by a call to that function. You may call a function from anywhere JavaScript Venkat within the page (or even from other pages if the function is embedded in an external .js file). Functions are defined at the beginning of a page, in the <head> section.

JavaScript Functions: Example <html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!") } </script> JavaScript Venkat </head> <body> <form> <input type="button" value="Click me! onclick="displaymessage()" > </form> </body> </html>

How to Define a Function? The syntax for creating a function is: function functionname(var1,var2,...,varX) { some code } var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function. JavaScript Venkat Note: A function with no parameters must include the parentheses () after the function name: function functionname() { some code }

How to Define a Function? Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function JavaScript Venkat with the exact same capitals as in the function name.

The return Statement Thereturnstatementisusedtospecifythevaluethatisreturnedfromthefunction. So,functionsthatisgoingtoreturnavaluemustusethereturnstatement. Example Thefunctionbelowshouldreturntheproductoftwonumbers(aandb): JavaScriptVenkatfunction total(a,b) { x=a*b; return x } Whenyoucallthefunctionabove,youmustpassalongtwoparameters: product = total(2,3) Thereturnedvaluefromthetotal()functionis6, anditwillbestoredinthevariablecalledproduct. ThereturnStatement Thereturnstatementisusedtospecifythevaluethatisreturnedfromthef unction. So,functionsthatisgoingtoreturnavaluemustusethereturnstatement. Example Thefunctionbelowshouldreturntheproductoftwonumbers(aandb): JavaScriptVenkatfunction total(a,b) { x=a*b; return x } Whenyoucallthefunctionabove,youmustpassalongtwoparameters: product = total(2,3) Thereturnedvaluefromthetotal()functionis6, anditwillbestoredinthevariablecalledproduct.

JavaScriptEvents EventsareactionsthatcanbedetectedbyJavaScript. JavaScriptVenkatJavaScriptEvents EventsareactionsthatcanbedetectedbyJavaScript. JavaScriptVenkat

JavaScriptVenkatJavaScriptVenkat Events ByusingJavaScript,wehavetheabilitytocreatedynamicwebpages. Examplesofevents: Amouseclick Awebpageoranimageloading Mousingoverahotspotonthewebpage Selectinganinputbo xinanHTMLform SubmittinganHTMLform Akeystroke Note:Eventsarenormallyusedincombinationw ithfunctions,andthefunctionwillnotbeexecutedbeforetheeventoccurs!

Events Some(butnotall)elementsonthewebpagerespondtouserinteractivity(keystrokes, mouseclicks)bycreatingevents Differentkindsofelementsproducedifferentevents Browsers arenotallalikeinwhateventsareproduced WewillconcentrateoneventsfromHTMLformelement sandJavaScriptVenkatcommonlyrecognizedevents YoucanputhandlersonHTMLformelements Ift heeventisn tgenerated,thehandlerdoesnothing Ahandlershouldbeveryshort Mosthandlerscall afunctiontodotheirworkEvents Some(butnotall)elementsonthewebpagerespondtouserinter activity(keystrokes, mouseclicks)bycreatingevents Differentkindsofelementsproducedifferentevents Browsers arenotallalikeinwhateventsareproduced WewillconcentrateoneventsfromHTMLformelement sandJavaScriptVenkatcommonlyrecognizedevents YoucanputhandlersonHTMLformelements Ift heeventisn tgenerated,thehandlerdoesnothing Ahandlershouldbeveryshort Mosthandlerscall afunctiontodotheirwork

Commonevents MostHTMLelementsproducethefollowingevents: onClick--theformelementisclicked onDblClick--theformelementisclickedtwiceinclosesuc cession onMouseDown--themousebuttonispressedwhileovertheformelement onMouseOver--the mouseismovedovertheformelementJavaScriptVenkatonMouseOverthemouseismovedoverthef ormelement onMouseOut--themouseismovedawayfromtheformelement onMouseUp--themousebutt onisreleasedwhileovertheformelement onMouseMove--themouseismoved InJavaScript,theses houldbespelledinalllowercaseCommonevents MostHTMLelementsproducethefollowingevents : onClick--theformelementisclicked onDblClick--theformelementisclickedtwiceinclosesuc cession onMouseDown--themousebuttonispressedwhileovertheformelement onMouseOver--the mouseismovedovertheformelementJavaScriptVenkatonMouseOverthemouseismovedoverthef ormelement onMouseOut--themouseismovedawayfromtheformelement onMouseUp--themousebutt onisreleasedwhileovertheformelement onMouseMove--themouseismoved InJavaScript,theses houldbespelledinalllowercase

onload and onUnload Event The onload and onUnload events are triggered when the user enters or leaves the page. The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onload and onUnload events are also often used to deal with cookies that should be set when a JavaScript Venkat user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome Venkat!".

onFocus, onBlur and onChange The onFocus, onBlur and onChange events are often used in combination with validation of form fields. Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the JavaScript Venkat user changes the content of the field: <input type="text" size="30" id="email" onchange = "checkEmail();">

JavaScript Venkat JavaScriptVenkat onSubmit TheonSubmiteventisusedtovalidateALLformfieldsbeforesubmittingit. BelowisanexampleofhowtousetheonSubmitevent. ThecheckForm()functionwillbecalledwhentheuserclicksthesubmitbuttonintheform. Ifthefieldvaluesarenotaccepted,thesubmitshouldbecancelled. ThefunctioncheckForm()returnseithertrueorfalse.Ifitreturnstruetheformwillbesubmit ted, otherwisethesubmitwillbecancelled: <formmethod="post"action="xxx.htm" onsubmit="returncheckForm()">

onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: JavaScript Venkat <a href="http://www.somedomain.com" onmouseover="alert('An onMouseOver event');return false"> <img src= image.gif" width="100" height="30"> </a>

A simple event handler <formmethod="post"action=""> <inputtype="button" name="myButton" value="Clickme" onclick="alert('Youclickedthebutton!');"> </form> ThebuttonisenclosedinaformThtiinputtype="button" JavaScriptVenkatThetagisinputtype=button ThenamecanbeusedbyotherJavaScriptcode Theva lueiswhatappearsonthebutton onclickisthenameoftheeventbeinghandled Thevalueoftheoncl ickelementistheJavaScriptcodetoexecute alertpopsupanalertboxwiththegiventextAsimpl eeventhandler <formmethod="post"action=""> <inputtype="button" name="myButton" value="Clickme" onclick="alert('Youclickedthebutton!');"> </form> ThebuttonisenclosedinaformThtiinputtype="button" JavaScriptVenkatThetagisinputtype=button ThenamecanbeusedbyotherJavaScriptcode Theva lueiswhatappearsonthebutton onclickisthenameoftheeventbeinghandled Thevalueoftheoncl ickelementistheJavaScriptcodetoexecute alertpopsupanalertboxwiththegiventext

Capitalization JavaScriptiscasesensitive HTMLisnotcasesensitive onclick="alert('Youcli ckedthebutton!');" TheunderlinedpartsareHTML ThequotedstringisJavaScript Youwillfrequentlyseeonclickcapi talizedasonClickJavaScriptVenkatYouwillfrequentlyseeonclickcapitalizedasonClick Th eJavanamingconventioniseasiertoread ThisisfineinHTML,butanerrorifitoccursinJavaScr ipt Alsonote:Sincewehaveaquotedstringinsideanotherquotedstring,weneedbothsingleand doublequotesCapitalization JavaScriptiscasesensitive HTMLisnotcasesensitive onclick="a lert('Youclickedthebutton!');" TheunderlinedpartsareHTML ThequotedstringisJavaScript Youwillfrequentlyseeonclickcapi talizedasonClickJavaScriptVenkatYouwillfrequentlyseeonclickcapitalizedasonClick Th eJavanamingconventioniseasiertoread ThisisfineinHTML,butanerrorifitoccursinJavaScr ipt Alsonote:Sincewehaveaquotedstringinsideanotherquotedstring,weneedbothsingleand doublequotes

Example: Simple rollover The following code will make the text Hello red when the mouse moves over it, and blue when the mouse moves away <h1 onMouseOver="style.color='red';" onMouseOut="style.color='blue';">Hello </h1> JavaScript Venkat Image rollovers are just as easy: <img src="../Images/duke.gif" width="55" height="68" onMouseOver="src='../Images/duke_wave.gif';" onMouseOut="src='../Images/duke.gif';">

Events and event handlers I Event Applies to Occurs when Handler Load Document body User loads the page in a browser onLoad Unload Document body User exits the page onUnload JavaScript Venkat Error Images, window Error on loading an image or a window onError Abort Images User aborts the loading of an image onAbort

Events and event handlers II Event Applies to Occurs when Handler KeyDown Documents, images, links, text areas User depresses a key onKeyDown KeyUp Documents, images, links, text areas User releases a key onKeyUp JavaScript Venkat KeyPress Documents, images, links, text areas User presses or holds down a key onKeyPress Change Text fields, text areas, select lists User changes the value of an element onChange

Events and event handlers III Event Applies to Occurs when Handler MouseDown Documents, buttons, links User depresses a mouse button onMouseDown MouseUp Documents, buttons, links User releases a mouse button onMouseUp JavaScript Venkat Click Buttons, radio buttons, checkboxes, submit buttons, reset buttons, links User clicks a form element or link onClick

Events and event handlers IV Event Applies to Occurs when Handler MouseOver Links User moves cursor over a link onMouseOver MouseOut Areas, links User moves cursor out of an image onMouseOut JavaScript Venkat map or link Select Text fields, text areas User selects form element s input field onSelect

Events and event handlers V Event Applies to Occurs when Handler Move Windows User or script moves a window onMove Resize Windows User or script resizes a onResize JavaScript Venkat window DragDrop Windows User drops an object onto the browser window onDragDrop

Events and event handlers VI Event Applies to Occurs when Handler Focus Windows and all form elements User gives element input focus onFocus Blur Windows and all form elements User moves focus to some other onBlur JavaScript Venkat element Reset Forms User clicks a Reset button onReset Submit Forms User clicks a Submit button onSubmit

JavaScript Objects Array Boolean Date Math StiJavaScriptVenkat String HTMLDOMJavaScriptObjects Array Boolean Da JavaScriptVenkat String HTMLDOM

ArrayObject TheArrayobjectisusedtostoreasetofvaluesinasinglevariablename. Eachvalueisanelementofthearrayandhasanassociatedindexnumber. JavaScriptVenkat YoucreateaninstanceoftheArrayobjectwiththe"new"keyword. ArrayObject TheArrayobjectisusedtostoreasetofvaluesinasinglevariablename. Eachvalueisanelementofthearrayandhasanassociatedindexnumber. JavaScriptVenkat YoucreateaninstanceoftheArrayobjectwiththe"new"keyword.

ArrayObject-Example Thefollowingexamplecreatestwoarrays,bothofthreeelements: varfamily_names=newArray(3) varfamily_names=newArray("Tove","Jani","Stale") JavaScriptVenkat Youcanrefertoaparticularelementinthearraybyusingthenameofthearray andtheindexnumber. Theindexnumberstartsat0. ArrayObject-Example Thefollowingexamplecreatestwoarrays,bothofthreeelements: varfamily_names=newArray(3) varfamily_names=newArray("Tove","Jani","Stale") JavaScriptVenkat Youcanrefertoaparticularelementinthearraybyusingthenameofthearray andtheindexnumber. Theindexnumberstartsat0.

ArrayObjectMethodsMethodDescriptionconcat()Joinstwoormorearraysandreturnstheresu ltjoin()Putsalltheelementsofanarrayintoastring.Theelementsareseparatedbyaspecifi eddelimiterpop()RemovesandreturnsthelastelementofanJavaScriptVenkatarraypush()Ad dsoneormoreelementstotheendofanarrayandreturnsthenewlengthreverse()Reversestheor deroftheelementsinanarraysort()SortstheelementsofanarrayArrayObjectMethodsMethod Descriptionconcat()Joinstwoormorearraysandreturnstheresultjoin()Putsalltheelemen tsofanarrayintoastring.Theelementsareseparatedbyaspecifieddelimiterpop()Removesa ndreturnsthelastelementofanJavaScriptVenkatarraypush()Addsoneormoreelementstothe endofanarrayandreturnsthenewlengthreverse()Reversestheorderoftheelementsinanarra ysort()Sortstheelementsofanarray

Theconcat()method DefinitionandUsage Theconcat()methodisusedtojointwoormorearrays. Thismethoddoesnotchangetheexistingarrays,itonlyreturnsacopyfthjidJavaScriptVenkat ofthejoinedarrays. Syntax arrayObject.concat(arrayX,arrayX,......,arrayX) Theconcat()method DefinitionandUsage Theconcat()methodisusedtojointwoormorearrays. Thismethoddoesnotchangetheexistingarrays,itonlyreturnsacopyfthjidJavaScriptVenkat ofthejoinedarrays. Syntax arrayObject.concat(arrayX,arrayX,......,arrayX)

The concat() method - Example Here we create two arrays and show them as one using concat(): <script type="text/javascript"> var arr = new Array(3) arr[0] = "Jani arr[1] = "Tove arr[2] = "Hege The output of the code will be: Jani,Tove,Hege,John,Andy,Wendy JavaScript Venkat var arr2 = new Array(3) arr2[0] = "John arr2[1] = "Andy arr2[2] = "Wendy document.write(arr.concat(arr2)) </script>

The join() method Inthisexamplewewillcreateanarray,andthenputalltheelementsinastring: <script type="text/javascript"> var arr = new Array(3) arr[0] = "Jani arr[1] = "Hege The output of the code will be:Jani,Hege,Stale JavaScriptVenkatarr[1] = Hege arr[2] = "Stale document.write(arr.join() + "<br />") document.write(arr.join(".")) </script> Jani,Hege,StaleJani.Hege.Stale Thejoin()method Inthisexamplewewillcreateanarray,andthenputalltheelementsinastring : <script type="text/javascript"> var arr = new Array(3) arr[0] = "Jani arr[1] = "Hege The output of the code will be:Jani,Hege,Stale JavaScriptVenkatarr[1] = Hege arr[2] = "Stale document.write(arr.join() + "<br />") document.write(arr.join(".")) </script> Jani,Hege,StaleJani.Hege.Stale

Thepop()method Inthisexamplewewillcreateanarray,andthenremovethelastelementofthear ray.Notethatthiswillalsochangethelengthofthearray: <scripttype="text/javascript"> vararr=newArray(3) arr[0]="Jani [1]"H The output of the code will be:Jani,Hege,Stale Stale JavaScriptVenkatarr[1]="Hege arr[2]="Stale document.write(arr+"<br/>") document.write(arr.pop()+"<br/>") document.write(arr) </script> Stale Jani,Hege Thepop()method Inthisexamplewewillcreateanarray,andthenremovethelastelementofthear ray.Notethatthiswillalsochangethelengthofthearray: <scripttype="text/javascript"> vararr=newArray(3) arr[0]="Jani [1]"H The output of the code will be:Jani,Hege,Stale Stale JavaScriptVenkatarr[1]="Hege arr[2]="Stale document.write(arr+"<br/>") document.write(arr.pop()+"<br/>") document.write(arr) </script> Stale Jani,Hege

Thepush()method Inthisexamplewewillcreateanarray,andthenchangethelengthofitbyaddin gaelement:<script type="text/javascript"> var arr = new Array(3) arr[0] = "Jani arr[1] = "Hege [2] "St l The output of the code will be:Jani,Hege,Stale 4 Jani Hege Stale Kai Jim JavaScriptVenkatarr[2] = "Stale document.write(arr + "<br />") document.write(arr.push("Kai Jim") + "<br />") document.write(arr) </script> Jani,Hege,Stale,Kai Jim Thepush()method Inthisexamplewewillcreateanarray,andthenchangethelengthofitbyaddin gaelement:<script type="text/javascript"> var arr = new Array(3) arr[0] = "Jani arr[1] = "Hege [2] "St l The output of the code will be:Jani,Hege,Stale 4 Jani Hege Stale Kai Jim JavaScriptVenkatarr[2] = "Stale document.write(arr + "<br />") document.write(arr.push("Kai Jim") + "<br />") document.write(arr) </script> Jani,Hege,Stale,Kai Jim

Thereverse()method Inthisexamplewewillcreateanarray, andthenreversetheorderofit: <script type="text/javascript"> var arr = new Array(3) arr[0] = "Jani arr[1] = "Hege The output of the code will be:Jani,Hege,Stale JavaScriptVenkatarr[1] = Hege arr[2] = "Stale document.write(arr + "<br />") document.write(arr.reverse()) </script> Stale,Hege,Jani Thereverse()method Inthisexamplewewillcreateanarray, andthenreversetheorderofit: <script type="text/javascript"> var arr = new Array(3) arr[0] = "Jani arr[1] = "Hege The output of the code will be:Jani,Hege,Stale JavaScriptVenkatarr[1] = Hege arr[2] = "Stale document.write(arr + "<br />") document.write(arr.reverse()) </script> Stale,Hege,Jani

Thesort()method Inthisexamplewewillcreateanarrayandsortitalphabetically: <scripttype="text/javascript"> vararr=newArray(6) arr[0]="Jani arr[1]="Hege arr[2]="Stale The output of the code will be: Jani,Hege,Stale,Kai Jim,Borge,Tove JavaScriptVenkatarr[2]=Stalearr[3]="KaiJim arr[4]="Borge arr[5]="Tove document.write(arr+"<br/>") document.write(arr.sort()) </script> Jani,Hege,Stale,Kai Jim,Borge,ToveBorge,Hege,Jani,Kai Jim,Stale,Tove Thesort()method Inthisexamplewewillcreateanarrayandsortitalphabetically: <scripttype="text/javascript"> vararr=newArray(6) arr[0]="Jani arr[1]="Hege arr[2]="Stale The output of the code will be: Jani,Hege,Stale,Kai Jim,Borge,Tove JavaScriptVenkatarr[2]=Stalearr[3]="KaiJim arr[4]="Borge arr[5]="Tove document.write(arr+"<br/>") document.write(arr.sort()) </script> Jani,Hege,Stale,Kai Jim,Borge,ToveBorge,Hege,Jani,Kai Jim,Stale,Tove

BooleanObject TheBooleanobjectisanobjectwrapperforaBooleanvalueanditisusedtoconver tanon-BooleanvaluetoaBooleanvalue,eithertrueorfalse. JavaScriptVenkat IftheBooleanobjecthasnoinitialvalueorifitis0,null,"",false,orNaN, theinitialvalueisfalse.Otherwiseitistrue(evenwiththestring"false"). BooleanObject TheBooleanobjectisanobjectwrapperforaBooleanvalueanditisusedtoconver tanon-BooleanvaluetoaBooleanvalue,eithertrueorfalse. JavaScriptVenkat IftheBooleanobjecthasnoinitialvalueorifitis0,null,"",false,orNaN, theinitialvalueisfalse.Otherwiseitistrue(evenwiththestring"false").

Boolean Object Examples 1 All the following lines of code create Boolean objects with an initial value of false: var b1=new Boolean() var b2=new Boolean(0) JavaScript Venkat var b3=new Boolean(null) var b4=new Boolean("") var b5=new Boolean(false) var b6=new Boolean(NaN)

Boolean Object Examples 2 All the following lines of code create Boolean objects with an initial value of true: var b1=new Boolean(true) var b2=new Boolean("true") JavaScript Venkat var b3=new Boolean("false") var b4=new Boolean( Venkat")

JavaScript Date Object TheDateobjectisusedtoworkwithdatesandtimes. TocreateaninstanceoftheDateobjectandassignittoavariablecalled"d",youdothefollowin g: var d=new Date() JavaScriptVenkat AftercreatinganinstanceoftheDateobject, youcanaccessallthemethodsoftheDateobjectfromthe"d"variable. Toreturnthecurrentdayinamonth(from1-31)ofaDateobject,writethefollowing: d.getDate() JavaScriptDateObject TheDateobjectisusedtoworkwithdatesandtimes. TocreateaninstanceoftheDateobjectandassignittoavariablecalled"d",youdothefollowin g: var d=new Date() JavaScriptVenkat AftercreatinganinstanceoftheDateobject, youcanaccessallthemethodsoftheDateobjectfromthe"d"variable. Toreturnthecurrentdayinamonth(from1-31)ofaDateobject,writethefollowing: d.getDate()

DateObjectMethodsMethodDescriptionDate()Returnstoday'sdateandtimegetDate()Return sthedayofthemonthfromaDateobject(from1-31) getDay()ReturnsthedayoftheweekfromaDateobject(from0-6) Mh() JavaScriptVenkatgetMonth()ReturnsthemonthfromaDateobject(from0-11) getFullYear()Returnstheyear,asafour-digitnumber, fromaDateobjectgetYear()Returnstheyear,asatwo-digitorafourdigitnumber,fromaDateobject.UsegetFullYear()instead!! DateObjectMethodsMethodDescriptionDate()Returnstoday'sdateandtimegetDate()Return sthedayofthemonthfromaDateobject(from1-31) getDay()ReturnsthedayoftheweekfromaDateobject(from0-6) Mh() JavaScriptVenkatgetMonth()ReturnsthemonthfromaDateobject(from0-11) getFullYear()Returnstheyear,asafour-digitnumber, fromaDateobjectgetYear()Returnstheyear,asatwo-digitorafourdigitnumber,fromaDateobject.UsegetFullYear()instead!!

DateObjectMethodsMethodDescriptiongetHours()ReturnsthehourofaDateobject(from023) getMinutes()ReturnstheminutesofaDateobject(from0-59) getSeconds()ReturnsthesecondsofaDateobject(from0-59) JavaScriptVenkatgetTime()ReturnsthenumberofmillisecondssincemidnightJan1,1970set Date()SetsthedayofthemonthinaDateobject(from1-31) setTime()Calculatesadateandtimebyaddingorsubtractingaspecifiednumberofmillisecon dsto/frommidnightJanuary1,1970DateObjectMethodsMethodDescriptiongetHours()Return sthehourofaDateobject(from023) getMinutes()ReturnstheminutesofaDateobject(from0-59) getSeconds()ReturnsthesecondsofaDateobject(from0-59) JavaScriptVenkatgetTime()ReturnsthenumberofmillisecondssincemidnightJan1,1970set Date()SetsthedayofthemonthinaDateobject(from1-31) setTime()Calculatesadateandtimebyaddingorsubtractingaspecifiednumberofmillisecon dsto/frommidnightJanuary1,1970

JavaScriptMathObject Thebuilt-inMathobjectincludesmathematicalconstantsandfunction s. YoudonotneedtocreatetheMathobjectbeforeusingit. JavaScriptVenkatJavaScriptMathObject Thebuilt-inMathobjectincludesmathematicalcons tantsandfunctions. YoudonotneedtocreatetheMathobjectbeforeusingit. JavaScriptVenkat

JavaScript Math Object : Methods Method Description abs(x) Returns the absolute value of a number ceil(x) Returns the value of a number rounded upwards to the nearest integer pow(x,y) Returns the value of x to the power of y floor(x) Returns the value of a number rounded downwards to the nearest integer JavaScript Venkat log(x) Returns the natural logarithm (base E) of a number max(x,y) Returns number with the highest value of x and y min(x,y) Returns the number with the lowest value of x and y random() Returns a random number between 0 and 1 round(x) Rounds a number to the nearest integer sqrt(x) Returns the square root of a number

JavaScript String Object Method Description big() Displays a string in a big font blink() Displays a blinking string bold() Displays a string in bold charAt(n) Returns the character at a specified position indexOf(chr) Returns the position of the first occurrence of a specified string value in a string JavaScript Venkat match(str) Searches for a specified string value in a string replace() Replaces some characters with some other characters in a string substr() Extracts a specified number of characters in a string, from a start index toLowerCase() Displays a string in lowercase letters toUpperCase() Displays a string in uppercase letters

JavaScript HTML DOM Objects With JavaScript you can access and manipulate all of the HTML DOM objects. JavaScript Venkat

HTML DOM TheHTMLDocumentObjectModel(HTMLDOM)definesastandardwayforaccessingandmanipulating HTMLdocuments. TheDOMpresentsanHTMLdocumentJavaScriptVenkatasatreestructure,andgivesaccesstothes tructurethroughasetofobjects. HTMLDOM TheHTMLDocumentObjectModel(HTMLDOM)definesastandardwayforaccessingandmanip ulatingHTMLdocuments. TheDOMpresentsanHTMLdocumentJavaScriptVenkatasatreestructure,andgivesaccesstothes tructurethroughasetofobjects.

WhatistheDOM? "TheW3CDocumentObjectModel(DOM)isaplatformandlanguageneutralinterfacethatallowspr ogramsandscriptstodynamicallyaccessandupdatethecontent,structure,andstyleofadocu ment." TheW3CDOMprovidesastandardsetofobjectsforrepresentingHTMLandXMLdocuments,andastan dardinterfaceforaccessingandmanipulatingthem. TheDOMisseparatedintodifferentparts(Core,XML,andJavaScriptVenkatHTML)anddifferent levels(DOMLevel1/2/3): CoreDOM-definesastandardsetofobjectsforanystructureddocument XMLDOM-definesastandar dsetofobjectsforXMLdocuments HTMLDOM-definesastandardsetofobjectsforHTMLdocumentsW hatistheDOM? "TheW3CDocumentObjectModel(DOM)isaplatformandlanguageneutralinterfacethatallowspr ogramsandscriptstodynamicallyaccessandupdatethecontent,structure,andstyleofadocu ment." TheW3CDOMprovidesastandardsetofobjectsforrepresentingHTMLandXMLdocuments,andastan dardinterfaceforaccessingandmanipulatingthem. TheDOMisseparatedintodifferentparts(Core,XML,andJavaScriptVenkatHTML)anddifferent levels(DOMLevel1/2/3): CoreDOM-definesastandardsetofobjectsforanystructureddocument XMLDOM-definesastandar dsetofobjectsforXMLdocuments HTMLDOM-definesastandardsetofobjectsforHTMLdocuments

What is the HTML DOM? The HTML DOM is the Document Object Model for HTML The HTML DOM is platform and language independent The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents The HTML DOM is a W3C standard The HTML DOM views HTML documents as a tree JavaScript Venkat structure of elements embedded within other elements. All elements, their containing text and their attributes, can be accessed through the DOM tree. Their contents can be modified or deleted, and new elements can be created by the DOM. The elements, their text, and their attributes are all known as nodes.

We Will Use VBScript TheHTMLDOMisplatformandlanguageindependent.Itcanbeusedbyanyprogramminglanguagelik eJava,JavaScript,andVBScript. InthistrainingwewilluseJavaScript. JavaScriptVenkatWeWillUseVBScript TheHTMLDOMisplatformandlanguageindependent.Itcan beusedbyanyprogramminglanguagelikeJava,JavaScript,andVBScript. InthistrainingwewilluseJavaScript. JavaScriptVenkat

DocumentObjects TheHTMLDOMdefinesHTMLdocumentsasacollectionofobjects. ThedocumentobjectistheparentofalltheotherobjectsinanHTMLdocument. ThdtbdbjttJavaScriptVenkat Thedocument.bodyobjectrepresentsthe<body>elementoftheHTM Ldocument. Thedocumentobjectistheparentofthebodyobject,andthebodyobjectisachildofthedocument object. DocumentObjects TheHTMLDOMdefinesHTMLdocumentsasacollectionofobjects. ThedocumentobjectistheparentofalltheotherobjectsinanHTMLdocument. ThdtbdbjttJavaScriptVenkat Thedocument.bodyobjectrepresentsthe<body>elementoftheHTM Ldocument. Thedocumentobjectistheparentofthebodyobject,andthebodyobjectisachildofthedocument object.

ObjectProperties HTMLdocumentobjectscanhaveproperties(alsocalledattributes). Thedocument.bgColorpropertydefinesthebackgroundcolorofthebodyobject. JavaScriptVenkat Thestatementdocument.bgColor="yellow"intheexampleabove,setsthebac kgroundcoloroftheHTMLdocumenttoyellow. ObjectProperties HTMLdocumentobjectscanhaveproperties(alsocalledattributes). Thedocument.bgColorpropertydefinesthebackgroundcolorofthebodyobject. JavaScriptVenkat Thestatementdocument.bgColor="yellow"intheexampleabove,setsthebac kgroundcoloroftheHTMLdocumenttoyellow.

ObjectEvents HTMLdocumentobjectscanrespondtoevents. Theonclick="ChangeColor()"attributeofthe<body>elementintheexampleabove,definesana ctiontotakeplaceJavaScriptVenkatwhentheuserclicksonthedocument. ObjectEvents HTMLdocumentobjectscanrespondtoevents. Theonclick="ChangeColor()"attributeofthe<body>elementintheexampleabove,definesana ctiontotakeplaceJavaScriptVenkatwhentheuserclicksonthedocument.

The HTML DOM Hierarchy JavaScript Venkat

Built-In Objects in DOM Window Object Document Object History Object Navigator Object JavaScript Venkat Images Object Forms Object Element Object

The Window Object TheWindowobjectcorrespondstothebrowserwindow.AWindowobjectiscreatedautomaticallyw itheveryinstanceofa<body>or<frame>tag. TheWindowobject'scollections, JavaScriptVenkatobjects,properties,methods,andeventsaredescribedinnextslide: TheWindowObject TheWindowobjectcorrespondstothebrowserwindow.AWindowobjectiscreate dautomaticallywitheveryinstanceofa<body>or<frame>tag. TheWindowobject'scollections, JavaScriptVenkatobjects,properties,methods,andeventsaredescribedinnextslide:

Window Object Properties, Methods Property Description Status Message Appears on the status bar document Refers to the current document being displayed frames Array consists of all the frames contained in the window history Refers to the windows history object length Identifies the number of frames contained in a window Methods Description JavaScript Venkat open( ) Opens a new window object close( ) Closes the specified window setTimeout() Invokes a function after a timeout period has elapsed clearTimeout() Clears a previously set timer setInterval( ) After every given milliseconds the specified function will be called clearInterval() Clears a previously set interval

Window Object - Examples Opening and Closing a window Using open() and close() Example0 Simple Dialogs Using alert(), confirm() and prompt() Example1 Status Line defaultStatus property JavaScript Venkat Example2 Timeout Processing Using setTimeout() & clearTimeout() Example3 Working with Intervals Using setInterval() & clearInterval() Example4

The Document Object TheDocumentobjectisusedtoaccessallelementsinapage. TheDocumentobject'scollections, properties,methods,andeventsaredescribedbelow: JavaScriptVenkatTheDocumentObject TheDocumentobjectisusedtoaccessallelementsinapag e. TheDocumentobject'scollections, properties,methods,andeventsaredescribedbelow: JavaScriptVenkat

Document Properties, Methods Property Description bgColor Identifies the bgcolor attribute of <BODY> tag forms An Array of all document <FORM> tag history The current browser s history list images An Array of all document <IMG> tag links AnArray of all document <A> tag Methods Description JavaScript Venkat write( ) Writes a string to a document clear( ) Clears the document from the window Events Usage onLoad Executed from <BODY> or <FRAMESET> tag onUnload Executed from <BODY> or <FRAMESET> tag

The History Object TheHistoryobjectisapredefinedobjectwhichcanbeaccessedthroughthehistorypropertyoft heWindowobject. TheHistoryobjectconsistsofanarrayofURLs.TheseURLsaretheURLstheuserhasvisitedwithi nabrowserwindow. JavaScriptVenkat Note:TheHistoryobjectisnotaW3Cstandard. TheHistoryobject'spropertiesandmethodsaredescribedbelow: TheHistoryObject TheHistoryobjectisapredefinedobjectwhichcanbeaccessedthroughthehi storypropertyoftheWindowobject. TheHistoryobjectconsistsofanarrayofURLs.TheseURLsaretheURLstheuserhasvisitedwithi nabrowserwindow. JavaScriptVenkat Note:TheHistoryobjectisnotaW3Cstandard. TheHistoryobject'spropertiesandmethodsaredescribedbelow:

History Properties, Methods Property Description length Number of entries in the history object Methods Description back( ) Loads the previous URL in history list forward() Loads the next URL in history list go( ) Forces the browser to go to a specific URL JavaScript Venkat

The Navigator Object TheNavigatorobjectcontainsinformationabouttheclientbrowser. Note:TheNavigatorobjectisnotaW3Cstandard. TheNavigatorobject'scollections, JavaScriptVenkatpropertiesandmethodsaredescribedbelow: TheNavigatorObject TheNavigatorobjectcontainsinformationabouttheclientbrowser. Note:TheNavigatorobjectisnotaW3Cstandard. TheNavigatorobject'scollections, JavaScriptVenkatpropertiesandmethodsaredescribedbelow:

Navigator Properties, Methods Property Description appName Name of the browser appVersion Browser Version platform Indicates the platform browserLa Language used by the browser JavaScript Venkat nguage Methods Description No Methods

Images Properties,MethodsPropertyDescriptionborderDefineswhetheraborderisdrawnorn otheight& widthReflectstheimageattributesHEIGHTandWIDTHJavaScriptVenkatnameImage snamesrcIma ge ssourceorURLMethodsDescriptionNoMethodsImaes Properties,MethodsPropertyDescriptio nborderDefineswhetheraborderisdrawnornotheight& widthReflectstheimageattributesHEIGHTandWIDTHJavaScriptVenkatnameImage snamesrcIma ge ssourceorURLMethodsDescriptionNoMethods

JavaScriptBestPractices1.Never,underanycircumstancesaddJavascriptdirectlytothedo cument. <scripttype"text/javascript"src"/scripts/library.js"></script> 2.Checktheavailabilityofanobjectbeforeaccessingitif(element){ ... } JavaScriptVenkat3.Essentialforeffectivedebuggingandstopsmosterrorshappening. 4.WriteJavascript,notbrowserspecificdialectsif(document.getElementByID(element){ ... } 5.Don'thijackotherscript'svariables. LocalvariablesonlyplacetheminsideafunctionJavaScriptBestPractices1.Never,underan ycircumstancesaddJavascriptdirectlytothedocument. <scripttype"text/javascript"src"/scripts/library.js"></script> 2.Checktheavailabilityofanobjectbeforeaccessingitif(element){ ... } JavaScriptVenkat3.Essentialforeffectivedebuggingandstopsmosterrorshappening. 4.WriteJavascript,notbrowserspecificdialectsif(document.getElementByID(element){ ... } 5.Don'thijackotherscript'svariables. Localvariablesonlyplacetheminsideafunction

JavaScriptBestPractices6.Don tgocrazy! Ifthereisnativesupportforabehaviour(suchasCSSpseudo-classes) thenusethem.They rebettersupportedandeasiertoimplement. 7.AssupportimprovesPresentationalScriptingwillbephasedoutformostaspects. BestPracticesareanevolvingsetofguidelinesthattaketheircuefromJavaScriptVenkatWeb StandardsandWebClients.Bepreparedforthis. 8.DevelopmentTechniquesCommentyourcodewell.Don tdouble-uponcode.Usesmallsnippets. 9.ThinkForwards,notBackwardsNomorebrowsersniffing!Insteaduseobjectdetection. 10.OptimizeyourcodeKeepadevelopercopy(fullycommented).Stripawayunnecessaryelemen ts keepitlean. JavaScriptBestPractices6.Don tgocrazy! Ifthereisnativesupportforabehaviour(suchasCSSpseudo-classes) thenusethem.They rebettersupportedandeasiertoimplement. 7.AssupportimprovesPresentationalScriptingwillbephasedoutformostaspects. BestPracticesareanevolvingsetofguidelinesthattaketheircuefromJavaScriptVenkatWeb StandardsandWebClients.Bepreparedforthis. 8.DevelopmentTechniquesCommentyourcodewell.Don tdouble-uponcode.Usesmallsnippets. 9.ThinkForwards,notBackwardsNomorebrowsersniffing!Insteaduseobjectdetection. 10.OptimizeyourcodeKeepadevelopercopy(fullycommented).Stripawayunnecessaryelemen ts keepitlean.

ThanksJavaScriptVenkatAnyQuestions? ThanksJavaScriptVenkatAnyQuestions?

You might also like