Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Script Lecturer Notes, Study notes of Javascript programming

An introduction to JavaScript, covering its history, capabilities, advantages, and limitations. It also discusses data types, operators, and statements in JavaScript, including conditional statements and switch statements. how to embed JavaScript in an HTML file and provides examples of arithmetic and string operators. useful for students studying web development or programming languages.

Typology: Study notes

2020/2021

Available from 04/20/2023

laxmiprasanna-muthyala
laxmiprasanna-muthyala 🇮🇳

1 document

Partial preview of the text

Download Java Script Lecturer Notes and more Study notes Javascript programming in PDF only on Docsity! JavaScript JavaScriptisthepremierclient-sideinterpretedscriptinglanguage.It‟swidelyusedin tasks rangingfrom thevalidationofform datatothecreationofcomplexuserinterfaces. DynamicHTMLisacombinationofthecontentformatedusingHTML,CSS,Scripting languageandDOM.Bycombiningalofthesetechnologies,wecancreateinteresting andinteractivewebsites.HistoryofJavaScript: NetscapeinitialyintroducedthelanguageunderthenameLiveScriptinanearlybeta releaseofNavigator2.0in1995,andthefocuswasonform validation.Afterthat,the languagewasrenamedJavaScript.AfterNetscapeintroducedJavaScriptinversion2.0 oftheirbrowser,MicrosoftintroducedacloneofJavaScriptcaledJScriptinInternet Explorer3.0. WhataJavaScriptcando? JavaScriptgiveswebdevelopersaprogramminglanguageforuseinwebpages& alowsthem todothefolowing: JavaScriptgivesHTMLdesignersaprogrammingtool JavaScriptcanbeusedtovalidatedata JavaScriptcanreadandwriteHTMLelements Createpop-upwindows Perform mathematicalcalculationsondata Reacttoevents,suchasauserrolingoveranimageorclickingabuton Retrievethecurrentdateandtimefrom auser‟scomputerorthelasttimeadocument wasmodified Determinetheuser‟sscreensize,browserversion,orscreenresolution JavaScriptcanputdynamictextintoanHTMLpage JavaScriptcanbeusedtocreatecookies AdvantagesofJavaScript: Lessserverinteraction Immediatefeedbacktothevisitors Increasedinteractivity Richerinterfaces Websurfersdon‟tneedaspecialplug-intouseyourscripts JavaScriptisrelativelysecure. LimitationsofJavaScript: WecannottreatJavaScriptasaful-fledgedprogramminglanguage.Itlackssomeof theimportantfeatureslike: Client-sideJavaScriptdoesnotalowthereadingorwritingoffiles.Thishasbeen keptforsecurityreason. JavaScriptcannotbeusedfornetworkingapplicationsbecausethereisnosuch supportavailable. JavaScriptdoesn'thaveanymultithreadingormultiprocesscapabilities. Ifyourscriptdoesn‟tworkthenyourpageisuseless. Pointstoremember:  JavaScriptiscase-sensitive  Eachlineofcodeisterminatedbyasemicolon  Variablesaredeclaredusingthekeywordvar  Scriptsrequireneitheramainfunctionnoranexitcondition.Therearemajor differencesbetweenscriptsandproperprograms.Executionofascriptstarts withthefirstlineofcode&runsuntilthereisnomorecode JavaScriptcomments: InJavaScript,eachlineofcommentisprecededbytwoslashesandcontinuesfrom that pointtotheendoftheline. //thisisjavascriptcomment BlockcommentsorMultilinecomments:/**/ #JavaScriptisnotthesameasJava,whichisabiggerprogramminglanguage (althoughtherearesomesimilarities) JavaScriptandHTMLPage HavingwritensomeJavaScript,weneedtoincludeitinanHTMLpage.Wecan‟t executethesescriptsfrom acommandline,astheinterpreterispartofthebrowser. Thescriptisincludedin thewebpageandrunbythebrowser,usualyassoonasthe pagehasbeenloaded.Thebrowserisabletodebugthescriptandcandisplayerrors. EmbeddingJavaScriptinHTMLfile: Ifwearewritingsmalscripts,oronlyuseourscriptsinfewpages,thentheeasiestway istoincludethescriptintheHTMLcode.Thesyntaxisshownbelow: <html> <head> <scriptlanguage=”javascript”> <!-- Javascriptcodehere //--> </head> <body> …… </body> </html> </script> </body> </html> DATATYPES •JavaScriptsupportsfiveprimitivedatatypes: numberstringbooleanundefinednul. •Thesetypesarereferredtoasprimitivetypesbecausetheyarethebasicbuilding blocksfrom whichmorecomplextypescanbebuilt. •Ofthefive,onlynumber,string,andbooleanarerealdatatypesinthesenseofactualy storingdata. •Undefinedandnularetypesthatariseunderspecialcircumstances. NumericDataType: Thesearenumbersandcanbeintegers(suchas2,22and2000)orfloating-point values(suchas23.42,-56.01,and2E45). ValidwaystospecifynumbersinJavaScript 10177.5-2.71.333333e77-1.7E123.E-5128e+100 Wecanrepresentintegersinoneofthefolowing3ways: Decimal:Theusualnumberswhicharehavingthebase10arethedecimalnumbers Octal:Octalliteralsbeginwithaleadingzero,andtheyconsistofdigitsfrom zero throughseven.Thefolowingarealvalidoctalliterals: 000777024513600 HexaDecimal:Hexadecimalliteralsbeginwithaleading0x,andtheyconsistofdigitsfrom 0through9andletersAthroughF.Thefolowingarealvalidhexadecimalliterals: 0x00XF8f000x1a3C5e7 Special Numeric Values: Specialvalue Resultof Comparisions Infinity,-Infinity Numbertoolargeortoo smal torepresent Alinfinityvaluescompare equaltoeachother NaN UndefinedOperation NaNnevercomparesequalto anything,eventoitself OperatorsinJavaScript TheoperatorsinJavaScriptcanbeclassifiedasfolows: Arithmeticoperators Relationaloperators Logicaloperators Assignmentoperators Arithmeticoperators: Note:Iftheargumentsof+arenumbersthentheyareaddedtogether.Ifthe argumentsarestringsthentheyareconcatenatedandresultisreturned. Example: <html> <body> <scriptlanguage="JavaScript"> <!- vara=5; ++a; alert("Thevalueofa="+a); -> </script> </body> </html> String(+)Operator: Example: txt1="Welcome"; txt2="toL&TInfotechLtd.!"; txt3=txt1+""+txt2; (or) txt1="Welcome"; txt2="toCMRCET.!"; Example: vars=“teststring”; alert(typeofs);//outputs“string” alert(typeof95);//outputs“number” alert(typeofwindow);//outputs “object”STATEMENTS Programsarecomposedoftwothings:dataandcode(setofstatements)which manipulatesthedata.JavascriptStatementscanbedividedintothefolowing categories: –ConditionalStatements –LoopingStatements –JumpingStatements Conditionalstatements:Conditionalstatementsareusedtomake decisions.VariousconditionalstatementsinJavaScript: Variousformsofif switch Variousformsofif: Simpleif if-elseStatement nestedif else-ifladder Example: <html> <body> <script language=“javascript”>vard =newDate(); vartime= d.getHours();if(time <10) document.write("<b>Goodmorning</b>"); else document.write("<b>Goodday</b>"); </script> <p>ThisexampledemonstratestheIf..Elsestatement.</p> <p>Ifthetimeonyourbrowserislessthan10,youwilgeta"Goodmorning"greeting. Otherwiseyouwilgeta"Goodday"greeting.</p> </body> </html> Output: switchstatement: Aswitchstatementalowsaprogram toevaluateanexpressionandatempttomatch theexpression'svaluetoacaselabel.Ifamatchisfound,theprogram executesthe associatedstatement. Syntax switch(expression) { caselabel1: block1break; caselabel2:block2 break; …. default:defblock; } Example: <html> <body> <script language=“javascript”>vard =newDate(); var theDay=d.getDay(); switch(theDay) { case5:document.write("<b>FinalyFriday</b>");break; case 6: document.write("<b>Super Saturday</b>"); break; case 0: document.write("<b>Sleepy Sunday</b>"); break; default: document.write("<b>I'm really looking forward to this weekend!</b>"); } </script> <p>This JavaScript will generate a different greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.</p> </body> </html> BasicArrayFunctions:Thebasicoperationsthatareperformedonarraysarecreation, additionofelements(insertingelements),accessingindividualelements,removing elements. CreatingArrays:Wecancreatearraysinseveralways: •vararrayObjectName=[element0,element1,..,elementN]; •vararrayObjectName=newArray(element0,element1,..,elementN); •vararrayObjectName=newArray(arrayLength); Ex: •varcolors=["Red","Green","Blue"]; •varcolors=newArray("Red","Green","Blue"); •varcolors=Array("Red","Green","Blue"); •varthirdArray=[,,]; •varfourthArray=[,35,,16,23,]; Note:JavaScriptarrayscanholdmixeddatatypesasthefolowingexample shows:vara=[“Monday”,34,45.7,“Tuesday”]; AccessingArrayElements: Arrayelementsareaccessedthroughtheirindex.Thelengthpropertycanbeusedto knowthelengthofthearray.Theindexvaluerunsfrom 0tolength-1. Example: <script language="javascript">vara =[1,2,3]; vars="; for(vari=0;i<a.length;i++) { s+=a[i]+""; } alert(s); </script> Addingelementstoanarray: Whathappensifwewanttoaddanitem toanarraywhichisalreadyful?Many languagesstrugglewiththisproblem.ButJavaScripthasarealygoodsolution:the interpretersimplyextendsthearrayandinsertsthenewitem. Ex:vara=[“vit”,”svecw”,”sbsp”]; a[3]=“bvrit”; a[10]=“bvrice”;//thisextendsthearrayandthevaluesofelementsa[4]toa[9]wilbe undefined. Modifyingarrayelements: Arrayelementvaluescanbemodifiedveryeasily. Ex:Tochangea[1]valueto“vdc”simplywrite: a[1]=“vdc”; SearchinganArray: Tosearchanarray,simplyreadeachelementonebyone&compareitwiththevaluethat wearelookingfor. RemovingArrayMembers: JavaScriptdoesn‟tprovideabuiltinfunctiontoremovearrayelement.Todothis,we canusethefolowingapproach: readeachelementinthearray iftheelementisnottheoneyouwanttodelete,copyitintoatemporaryarray ifyouwanttodeletetheelementthendonothing incrementtheloopcounter repeattheprocess finalystorethetemporaryarrayreferenceinthemainarray variableNote:Thestatementdeletea[0]makesthevalueofa[0] undefinedOBJECT-BASEDARRAYFUNCTIONS: InJavaScript,anarrayisanobject.So,wecanusevariousmemberfunctionsofthe objecttomanipulatearrays. concat() Theconcat()methodreturnsthearrayresultingfrom concatenatingargumentarraysto thearrayonwhichthemethodwasinvoked.Theoriginalarraysareunalteredbythis process. Syntax:array1.concat(array2[,array3,…arrayN]); Example: <script language="javascript">vara =[1,2,3]; varb=["a","b"]; alert(a.concat(b)); </script> join() join()methodalowstojointhearrayelementsasstringsseparatedbygiven specifier.Theoriginalarrayisunalteredbythisprocess. Syntax:arrayname.join(separator); Example: <script language="javascript">vara =[1,2,3];alert(a.join(“#”)); </script> push() push()functionaddsoneormoreelementstotheendofanarrayandreturnsthelast elementadded. Syntax:arrayname.push(element1[,element2,.elementN]); Example: <script language="javascript">vara =[1,2,3];alert(a.push(4,5)); //displays5 alert(a);//displays1,2,3,4,5 </script> pop() pop()removesthelastelementfrom thearrayandreturnsthatelement Syntax:arrayname.pop(); reverse() reverse()methodtransposestheelementsofanarray:thefirstarrayelement becomesthelastandthelastbecomesthefirst.Theoriginalarrayisalteredbythis process. Syntax:arrayname.reverse(); Example: <script language="javascript">vara =[1,2,3]; a.reverse(); alert(a); </script> shift() shift()removesthefirstelementofthearrayandindoingsoshortensitslengthbyone. Itreturnsthefirstelementthatisremoved. Ex:vara=[1,2,3]; varfirst=a.shift(); alert(a);//2,3 alert(first);//1 str1.concat(str2[,str3.strN]) Thismethodisusedtoconcatenatestringstogether.Forexample,s1.concat(s2)returns theconcatenatedstringofs1ands2.Theoriginalstringsdon‟tgetalteredbythis operation.substring(start[,end]) Thismethodreturnsthesubstringspecifiedbystartandendindices(uptoendindex, butnotthecharacteratendindex).Iftheendindexisnotspecified,thenthismethod returnssubstringfrom startindextotheendofthestring. Example:“vitsvecw”.substring(3,6);//returns sve“vitsvecw”.substring(3);//returnssvecw substr(index[,length]) Thismethodreturnssubstringofspecifiednumberofcharacters(length),starting from index.Ifthelengthisnotspecifieditreturnstheentiresubstringstartingfrom index. Example:“vitsvecw”.substr(3,2); //returnssv“vitsvecw”.substr(3); //returnssvecwtoLowerCase() returnsthestringinlowercase.Theoriginalstringisnotalteredbythisoperation. Example:<script language="javascript">var s="CMRcet"; alert(s.toLowerCase() );alert(s);/ </script> toUpperCase() returnsthestringinuppercase.Theoriginalstringisnotalteredbythisoperation. Example:<script language="javascript">vars="Cmrcet"; alert(s.toUpperCase());//displays alert(s); </script> split(separator[,limit]) Splitsthestringbasedontheseparatorspecifiedandreturnsthatarrayofsubstrings.If thelimit isspecifiedonlythosenumberofsubstringswilbereturned Example1:<scriptlanguage="javascript"> vars="vit#svecw#bvrice#sbsp"; vart =s.split("#"); alert(t); </script> Example2:<scriptlanguage="javascript"> vars="cse#ece#mech#it"; vart=s.split("#"); alert(t);//displayscse,ece,mech,it </script> WriteJavascriptthatdetermineswhetherthegivenstringispalindromeornot <html> <body> <scriptlanguage="javascript"> vars=prompt("enterany string");varn=s.length; varflag=true; for(vari=0;i<n;i++) { if(s.charAt(i)!=s.charAt(n-1-i)) { flag=false;break; } } if(flag)alert("palendrome"); elsealert("notpalendrome"); </script> </body> </html> STRINGMETHODSUSEDTOGENERATEHTML: string.anchor(“anchorname”)string.link(url) string.blink()string.big() string.bold()string.smal() string.fixed()string.strike() string.fontcolor(colorvalue) string.sub() string.fontsize(integer1to7) string.sup()string.italics() Example:<scriptlanguage="javascript"> vars="Test".bold();//svalueis:<b>Test</b> document.write(s); document.write("<br>"); document.write("CMRCET".italics()) ; </script> anchor ("name") Creates a named anchor specified by the <A> element using the argument name as the value af the corresponding attribute. ac x = "Marked point".anchor ("marker") ; ¥? <& NANE="macker">Marked point</ A> hig Creates a <BIG> element using the provided string. ar x = "Grow™.nig(); // <BIG>Grow</BIG> blinkg Creates a blinking text element enclosed by <BLINK> out of the provided string despite Internet Explorer's lack of support for the <BLINK> element. ar x = "Bad Metscape".b1link(): ¥? <BLINK>Bad Netscape</BLINK> bold) Creates a bold text element indicated by <B> out of the provided string ar x = "Behold! ".bold(): ff <B>Behold!</B> fixed) Creates a fixed width text element indicated by <TT> out of the provided string az x = "Code". fixed(): ff <TT>Code</TT> fontcolor {color} Creates a <FONT> tag with the calor specified by the argument color. The value passed should be a valid hexadecirnal string value or a string specifying a color name. ax x = "green". font ("green") 7 ¢/ <FONT COLOR="green">Green</FONT> ar x = "Red". fone ("#FFOOOO") : ¢/ <FONT COLOR="#FFO000">Red</FONT> fun(10,20);//functioncal fun("abc","vit");//function cal </script> </body> </html> Returningvalues Thereturnstatementisusedtospecifythevaluethatisreturnedfrom thefunction.So functionsthataregoingtoreturnavaluemustusethereturnstatement. Example: functionprod(a,b) { x=a*b;returnx; } ScopingRules: Programminglanguagesusualyimposerules,caledscoping,whichdeterminehowa variablecanbeaccessed.JavaScriptisnoexception.InJavaScriptvariablescanbe eitherlocalorglobal.global Globalscopingmeansthatavariableisavailabletoalpartsoftheprogram.Such variablesaredeclaredoutsideofanyfunction. local Localvariablesaredeclaredinsideafunction.Theycanonlybeusedbythatfunction. GLOBALFUNCTIONS EXCEPTIONHANDLING Runtimeerrorhandlingisvitalyimportantinalprograms.ManyOOPlanguagesprovide amechanism forhandlingwithgeneralclassesoferrors.Themechanism iscaled ExceptionHandling. Anexceptioninobject-basedprogramminglanguageisanobject,createddynamicalyat run-time,whichencapsulatesanerrorandsomeinformationaboutit.InJavaScriptit returnsanerrorobjectwhenanerrorisgeneratedatbrowserwhilethecodeisexecuting. try-catchblock Theblockofcodethatmightcausetheexceptionisplacedinsidetryblock.catchblock containsstatementsthataretobeexecutedwhentheexceptionarises. try{statement onestatement twostatement three }catch(Error){//Handleerrorshere}finaly{//executethecodeevenregardlessof abovecatchesarematched} try{ alert(„Thisiscodeinsidethetryclause‟); ablert(„Exceptionwilbethrownbythiscode‟); } catch(exception) { alert(“InternetExplorersaystheerroris“+exception.description); } throwstatement Thethrowstatementalowsustocreateanexception.Ifweusethisstatementtogether withthe try..catchstatement,wecancontrolprogram flowandgenerateaccurateerrormessages. Syntax throw(exception) Theexceptioncanbeastring,integer,Booleanoranobject Example: <html><body><scripttype="text/javascript">varx=prompt("Enteranumberbetween0and 10:",");try{if(x>10){throw"Error!Thevalueistoohigh“; }elseif(x<0){throw"Error!Thevalueistoolow“; }elseif(isNaN(x)){throw"Error!Thevalueisnotanumber";}}catch(er){alert(er);} </script></body></html> DocumentObjectModel(DOM) TheDOM defineswhatpropertiesofadocumentcanberetrievedandchanged,andthe methodsthatcanbeperformed.(or) TheBrowserDOM specifieshowJavaScript(andotherprogramminglanguages)can beusedtoaccessinformationaboutadocument.Thenyoucanperform calculations anddecisionsbasedonthevaluesretrievedfrom thedocumentusingJavaScript Example:Wecanretrievepropertiessuchasthevalueoftheheightatributeofanyimage, the hrefatributeofanylink,orthelengthofapasswordenteredintoatextboxinaform. Meanwhile,methodsalowustoperform actionssuchasreset()orsubmit()methods onaform thatalowsyoutoresetorsubmitaform. DOM Hierarchy Theobjectsinthewebpagefolowastricthierarchy,wherethewindowobjectisthe verytoplevel.Becausewindowisthetoplevel“root”objectitcanbeomitedinthe addresssyntax.Forinstance,thewindow.document.bgColorproperty,whichstoresthe valueofthewindow‟scurrentbackgroundcolor,canbeaddressedsimplyas document.bgColor SeveraloftheDOM objectshavepropertiesthatcontainanarrayofelementsinthat webpage.Forexample,withdocument.images[],theimages[]arrayisapropertyofthe BUILT-INOBJECTSINJAVASCRIPT Javascripthasmanybuilt-inobjectswhichpossesthecapabilityofperforming manytasks.HencesometimesJavascriptisreferredtoasanObjectbased programminglanguage. Nowwewildiscussfewcommonlyusedobjectsofjavascriptalongwiththeiratributes& behaviors. THEWINDOW OBJECT PROPERTIES: frames[] arrayofframesstoredintheorderinwhichtheyaredefinedinthedocument frames.length numberof framesself currentwindow opener thewindow(ifany)whichopenedthecurrentwindow parent parentofthecurrentwindowifusingaframeset status messageinthestatusbar defaultStatus defaultmessageforthestatusbar name thenameofthewindowifitwascreatedusingtheopen()methodandanamewas specified location thisobjectcontainsthefulURLaddressofthedocumentthatiscurrentlyloadedinthe browser,andassigninganewvaluetothiswilloadthespecifiedURLintothebrowser. AtypicalURLaddressmaycomprisetheseparts: Protocol://host/pathname?#hash Wecanusethefolowingpropertiesoflocationobjecttoextractindividualpiecesof informationfrom URL window.location.href window.location.protocol window.location.host window.location.pathnam ewindow.location.hash history Thewindow.historyobjectcontainshistory(i.e.arrayofURLaddressespreviously visitedduringabrowsersession).Forsecurityreasons,thesearenotdirectlyreadable buttheyareusedtonavigatebacktopreviouspages.Theback()andforward() methodsofthewindow.historyobjectemulatethebrowser‟sBackandForwardbutons. Moreflexiblenavigationisoftenprovidedbythewindow.history.go()method. Example:window.history.go(1) goesforwardtothenextpageinthe historywindow.history.go(-2) goesbackwardby2pagesinthehistory window.history.go(0) causesthebrowsertoreloadthecurrent document. Example: <html> <head> <script language="javascript"> functionfun() { varn=prompt("enteranynumber"); window.history.go(n); } </script> </head> <body> <form> <h1>CMRCET</h1> <h2>Medchal</h2> <inputtype="buton"value="navigate"onclick=fun()> </form> </body> </html> onload Thisobjectcanbeusedtospecifythenameofafunctiontobecaledimmediatelyafter adocumenthascompletelyloadedinthebrowser Example: <html> <head> <scriptlanguage="javascript"> window.onunload=fun; functionfun(){ alert("numberofframes="+window.frames.length); } </script> </head> <framesetrows="30%,30%,*"> <framename="row1"src="page1.html"> <framename="row2"src="page2.html"> <framename="row3"src="page3.html"> </frameset> </html> onunload Thisobjectcanbeusedtospecifythenameofafunctiontobecaledwhentheuserexits thewebpage. METHODS: alert(“string”) opensboxcontainingthemessage confirm(“string”) displaysamessageboxwithOKandCANCELbutons prompt(“string”) displaysapromptwindowwithfieldfortheusertoenteratextstring blur() removefocusfrom currentwindow focus() givefocustocurrentwindow scrol(x,y) movethecurrentwindowtothechosenx,ylocation open(“URL”,”name”,“optionsstring”) Theopen()methodhas3arguments: URLtoloadinthepop-upwindow Nameforthepop-up Listofoptions forms.length thenumberofform objectsonthepage links[] arrayoflinksinthecurrentpageintheorderinwhichtheyappearinthedocument anchors[] anarrayofanchors.AnynamedpointinsideanHTMLdocumentisananchor.Anchors arecreateusing<aname=…>.Thesewilbecommonlyusedformovingaroundinsidea largepage.Theanchorspropertyisanarrayofthesenamesintheorderinwhichthey appearintheHTMLdocument.Anchorscanbeaccessedlikethis:document.anchors[0] images[] anarrayofimages applets[] anarrayofapplets cookie objectthatstoresinformationaboutcookie Methods: write(“string”) writeanarbitrarystringtotheHTMLdocument writeln(“string”) writeastringtotheHTMLdocumentandterminateitwithanewlinecharacter.HTML pagescanbecreatedontheflyusingJavaScript.Thisisdoneusingthewriteorwriteln methodsofthedocumentobject. Example: document.write(“<body>”); document.write(“<h1>CMRCET</h1>”) ;document.write(“<form>”); clear() clearthecurrentdocument close() closethecurrentdocument getElementById() Returnsthereferenceoftheform controlgivenbyitsId DATEOBJECT Thisobjectisusedtoobtainthedateandtime.Thisdateandtimeisbasedon computer‟slocaltime(system‟stime)oritcanbebasedonGMT.ThisGMTisalso knownasUTCi.e.UniversalCoordinatedTime.Thisisbasicalyaworldtimestandard. Folowingarethecommonlyused methodsofDateobject: Method Meaning getTime() Itreturnsthenumberofmiliseconds.This valueisthedifferencebetweenthecurrent timeandthetimevaluefrom 1stJanuary 1970 getDate() Returnsthecurrentdatebasedon computerslocaltime getUTCDate() Returnsthecurrentdateobtainedfrom UTC getDay() Returnsthecurrentday.Thedaynumberis from 0to6i.e.from SundaytoSaturday getUTCDay() ReturnsthecurrentdaybasedonUTC.The daynumberisfrom 0to6 getHours() Returnsthehourvaluerangingfrom 0to23 getUTCHours() Returnsthehourvaluerangingfrom 0to 23,basedonUTCtimingzone getMinutes Returnstheminutevaluerangingfrom 0to 59 getUTCMinutes() Returnstheminutevaluerangingfrom 0to 59, basedonUTC getSeconds() Returnsthesecondsvaluerangingfrom 0to 59 getUTCSeconds() Returnsthesecondsvaluerangingfrom 0to59,basedonUTC getMiliseconds() Returnsthemilisecondsvalueranging from 0to999,basedonlocaltime getUTCMiliseconds() Returnsthemilisecondsvalueranging from 0to999,basedonUTC setDate(value) ThisisusedtosettheDate setHour(hr,min,sec,ms) ThisisusedtosettheHour Example: <html> <head> <title>DateObject</title> </head> <body> <script type="text/javascript">vard =newDate(); document.write("TheDateis:"+d.toString()+"<br>"); document.write("Todaydateis:"+d.getDate()+"<br>"); document.write("UTCdateis:"+d.getUTCDate()+"<br>"); document.write("Minutes: "+d.getMinutes()+"<br>"); document.write("UTC Minutes: "+d.getUTCMinutes()+"<br>"); Age: <input type="text" size=5> <br> </form> </body> </html> Form elements: Theelementsoftheform areheldinthearraywindow.document.forms[].elements[] Thepropertiesoftheform elementscanbeaccessedandsetusingJavascript. Theelementsoftheform areheldinthearraywindow.document.forms[].elements[] Thepropertiesoftheform elementscanbeaccessedandsetusingJavascript. Example1: <html> <head> <script language="javascript"> functionfun(){ varmsg="Elementtype:"+ document.forms.reg.elements[0].type;msg+="\nElementvalue: "+document.forms.reg.elements[0].value;window.alert(msg); } </script> </head> <body> <form id="reg"> <inputtype="buton"value="click"name="btn1"onClick="fun()"> </form> </body> </html> Example2: <!-Itisusefultochangethelabelthatisdisplayedonabutonbyitsvalueatributeifthat butonperformsdualactions -> <html> <head> <script language="javascript"> var running=false;varnum=0; vartim; function startstop(){running= !running;count(); document.forms[0].btn1.value=(running)?"stop":"start"; } function count(){if(runni ng){num++; window.status="secondselapsed:"+ num;tim =setTimeout("count()",1000); } else{ num=0;clearTimeout(tim); } } <body> <form id="form1"> Thebranchesinourcolegeare:<br> <inputtype="radio"name="rbnBranch"value="cse"selected>CSE<br> <inputtype="radio"name="rbnBranch"value="it">IT<br> <inputtype="radio"name="rbnBranch"value="ece">ECE<br> <inputtype="radio"name="rbnBranch"value="eee">EEE<br><br> <inputtype="buton"value="GetRadioInfo"onclick="radio_info()"> </form> </body> </html> Check Boxes Example: <html> <head> <script language="javascript"> functioninfo() { varmsg="1stradiostatus="+ document.forms[0].branch[0].checked;msg+="\n2ndradiostatus ="+document.forms[0].branch[1].checked;msg+="\n3rdradio status="+document.forms[0].branch[2].checked;msg+="\n4th radiostatus="+document.forms[0].branch[3].checked;alert(msg); } </script> </head> <body> <form id="form1"> Thebranchesinourcolegeare:<br> <inputtype="checkbox"name="branch"value="cse">CSE<br> <inputtype="checkbox"name="branch"value="it">IT<br> <inputtype="checkbox"name="branch"value="ece">ECE<br> <inputtype="checkbox"name="branch"value="eee">EEE<br><br> <inputtype="buton"value="GetInfo"onclick="info()"> </form> </body> </html> OptionLists The<option>tagcanbeusedinthe<select>tagtospecifyvariousoptionsinthe dropdownmenulist.Almenuitemsarestoredinthe<select>object‟soptions[] array.WecanusetheselectedIndexpropertyofoptionlisttoidentifytheindexof theselecteditem Example: <html> <head> <script language="javascript"> function get_selected(){ vars=document.forms[0].sltVehicle.selectedIndex; document.forms[0].txtVehicle.value= document.forms[0].sltVehicle.options[s].text; } </script> </head> <body> <form name="form1"> <selectname="sltVehicle"> <optionvalue="v">Volvo</option> <optionvalue="s"selected>Saab</option> <optionvalue="m">Mercedes</option> <optionvalue="a">Audi</option> </select> <inputtype="buton"value="ShowSelected"onClick="get_selected()"> <inputtype="text"size=15name="txtVehicle"> </form> </body> </html> Exercise:Writeaprogram thatdesignsaSimpleCalculator <html> <head> <script language="javascript">var exp="; function fun(ch){if(ch=='='){ calc.txt1.value=eval(exp);exp="; } else{ exp=exp+ch;calc.txt1.value=exp; } } </script> </head> <body> <form name="calc"> <tableborder=1> <tr> <thcolspan=3>Simplecalculator</th> </tr> <tr> <thcolspan=3><inputtype="text"name="txt1"size=15></th> </tr> <tr> <td><inputtype="buton"value="1"onclick="fun('1')"></td> <td><inputtype="buton"value="2"onclick="fun('2')"></td> <td><inputtype="buton"value="3"onclick="fun('3')"></td>  SecurityIssue:Browsersgeneralyonlyaccept20cookiespersiteand300 cookiestotal,andsincebrowserscanlimiteachcookieto4kilobytes,cookies cannotbeusedtofilupsomeone'sdiskorlaunchotherdenial-of-serviceatacks. History: CookieswereoriginalyinventedbyNetscapetogive'memory'towebserversand browsers.TheHTTPprotocol,whicharrangesforthetransferofwebpagestoyour browserandbrowserrequestsforpagestoservers,isstate-less,whichmeansthat oncetheserverhassentapagetoabrowserrequestingit,itdoesn'trememberathing aboutit.Soifyoucometothesamewebpageasecond,third,hundredthormilionth time,theserveronceagainconsidersittheveryfirsttimeyouevercamethere. Thiscanbeannoyinginanumberofways.Theservercannotrememberifyou identifiedyourselfwhenyouwanttoaccessprotectedpages,itcannotrememberyour userpreferences,itcannotrememberanything.Assoonaspersonalizationwas invented,thisbecameamajorproblem. Cookieswereinventedtosolvethisproblem.Thereareotherwaystosolveit,but cookiesareeasytomaintainandveryversatile. Howcookieswork? Acookieisnothingbutasmaltextfilethat'sstoredinyourbrowser.Itcontainssomedata: 1.Aname-valuepaircontainingtheactualdata 2.Anexpirydateafterwhichitisnolongervalid 3.Thedomainandpathoftheserveritshouldbesentto Assoonasyourequestapagefrom aserver(whichwasrequestedearlier&theserver sentcookietotheclient),thecookieisaddedtotheHTTPheader.Serversideprograms canthenreadouttheinformationandgiveresponseaccordingly.Soeverytimeyouvisit thesitethecookiecomesfrom,informationaboutyouisavailable.Thisisverynice sometimes,atothertimesitmaysomewhatendangeryourprivacy. CookiescanbereadbyJavaScripttoo.They'remostlyusedforstoringuserpreferences. name-value Eachcookiehasaname-valuepairthatcontainstheactualinformation.Thenameof thecookieisforyourbenefit,youwilsearchforthisnamewhenreadingoutthecookie information. Expirydate Eachcookiehasanexpirydateafterwhichitistrashed.Ifyoudon'tspecifytheexpiry datethecookieistrashedwhenyouclosethebrowser.Thisexpirydateshouldbein UTC(Greenwich)time. Domainandpath Eachcookiealsohasadomainandapath.Thedomaintelsthebrowsertowhich domainthecookieshouldbesent.Ifyoudon'tspecifyit,itbecomesthedomainofthe pagethatsetsthecookie. document.cookie Cookiescanbecreated,readanderasedbyJavaScript.Theyareaccessiblethroughthe propertydocument.cookie.Thoughyoucantreatdocument.cookieasifit'sastring,itisn't realy,andyouhaveonlyaccesstothename-valuepairs. IfIwanttosetacookieforthisdomainwithaname-valuepair'ppkcookie1=testcookie' thatexpiresinsevendaysfrom themomentIwritethissentence,Ido document.cookie='ppkcookie1=testcookie;expires=Thu,2Aug200120:47:11UTC; path=/'EventHandling Aneventisdefinedas“somethingthattakesplace”andthatisexactlywhatitmeansin webprogrammingaswel. AneventhandlerisJavaScriptcodethatisdesignedtoruneachtimeaparticularevent occurs. Syntaxforhandlingtheevents: <tagAtributesevent=“handler”> Table:JavaScriptEvents Event Handler Description blur onBlur Theinputfocusismoved from theobject change onChange Thevalueofafieldina form hasbeenchangedby theuserenteringordeleting data click onClick Themouseisclickedoveran elementofapage dblclick onDblClick Aform elementorlinkis clickedtwiceinrapid succession dragdrop onDragDrop Asystem fileisdragged withamouseanddropped ontothebrowser focus onFocus Inputfocusisgiventoan element.Thereverseofblur keydown onKeyDown Akeyispressedbut notreleased keypress onKeyPress Akeyispressed keyup onKeyUp Apressedkeyisreleased load onLoad Thepageisloadedbythe browser mousedown onMouseDow n Amousebutonispressed mousemove onMouseMov e Themouseismoved mouseo ut onMouseOut Themousepointermoves off anelement mouseover onMouseOver Themousepointermoves over anelement mouseu onMouseUp The mouse button is p released move onMove A window is moved, Example: <html> <head> <script language="javascript"> function change(v) { vari= document.getElementById("mouse"); if(v==1)i.src="over.gif"; elsei.src="out.gif"; } </script> </head> <body> <form name="form1"> <h1>DemonstratingRoloverButons</h1> <imgid="mouse"src="out.gif"width=100height=100onMouseOver=change(1) onMouseOut=change(0)> </form> </body> </html> RegularExpressions&PaternMatching ARegularexpressionisawayofdescribingapaterninapieceoftext.It‟san easywayofmatchingastringtoapatern. Wecouldwriteasimpleregularexpressionanduseittocheck,quickly,whetheror notanygivenstringisaproperlyformateduserinput.Thissavesusfrom difficulties andalowsustowritecleanandtightcode. Forinstance,ascriptmighttake“name”datafrom auserandhavetosearchthroughit checkingthatnodigitshavebeenentered.Thistypeofproblem canbesolvedby readingthroughthestringonecharacteratatimelookingforthetargetpatern. Althoughitseemslikeastraightforwardapproach,itisnot(Efficiency&speedmaters, soanycodethatdoeshastobewritencarefuly).Theusualapproachinscripting languagesistocreateapaterncaledaregularexpression,whichdescribesasetof charactersthatmaybepresentinastring. CreatingRegularExpressions: AregularexpressionisaJavaScriptobject.Wecancreateregularexpressionsin oneoftwoways.  Staticregularexpressions Ex:varregex=/fish/fowl/;  Dynamicregularexpressions Ex:varregex=newRegExp(“fish|fowl”); Note:Ifperformanceisanissueforourscript,thenweshouldtrytousestatic expressionswheneverpossible.Ifwedon‟tknow whatwearegoingto be searchinguntilruntime(forinstance,thepaternmaydependonuserinput)then wecreatedynamicpaterns Aregularexpressionpaterniscomposedofsimplecharacters,suchas/abc/,ora combinationofsimpleandspecialcharacters,suchas/ab*c/or/Chapter(\d+)\.\d*/. UsingSimplePaterns: •Simplepaternsareconstructedofcharactersforwhichwewanttofindadirectmatch. •Forexample,thepatern/abc/matchescharactercombinationsinstringsonlywhen exactlythecharacters'abc'occurtogetherandinthatorder. •Suchamatchwouldsucceedinthestrings "Hi,doyouknowyourabc's?“ "Thelatestairplanedesignsevolvedfrom slabcraft." •Inbothcasesthematchiswiththesubstring'abc'. •Thereisnomatchinthestring"Grabcrab"becauseitdoesnotcontainthesubstring'abc'. Usingspecialcharacters: •Whenthesearchforamatchrequiressomethingmorethanadirectmatch,suchas findingoneormoreb's,orfindingwhitespace,thepaternincludesspecialcharacters. •Forexample,thepatern/ab*c/matchesanycharactercombinationinwhicha single'a'isfolowedbyzeroormore'b's(*means0ormoreoccurrencesofthe precedingitem)andthenimmediatelyfolowedby'c'.Inthestring"cbbabbbbcdebc," thepaternmatchesthesubstring'abbbbc' WorkingwithRegularExpressions Regularexpressionpaternsinjavascriptmustbeginandendwithforwardslashes. .--Matchessinglecharacter \--identifiesthenextcharcterasaliteralvalue ^ Matchescharactersatbeginingofastring $Matchescharactersattheendofthestring ()--specifiesrequiredcharacterstoincludeinpatern match[]--Specifiesalternatecharactersalowedina paternmatch[̂]Specifiescharacterstoexcludeina paternmatch ~identifiesapossiblerangeofcharacterstomatch |Specifiesalternatesetsofcharacterstoinclude ĉircumflexoperator Javascriptcharacterclassescapecharacters: \wAlphanumericcharacter \DAlphabeticcharacters \dNumericchacters
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved