0% found this document useful (0 votes)
45 views

Module 2 - Front End Development

Uploaded by

Daivik Chaulkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
45 views

Module 2 - Front End Development

Uploaded by

Daivik Chaulkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 58
Syllabus Introduction to JavaScrt-JvaSept DOM Model Dato and Objets-Roguar Expressins- Exception Handing-Vabdaton-Builtinobjects-Event Handing, DHTML with JavaScit- JSON introduction ~ Sytax ~ Function Files - Http Request SQL, JavaScript: 2a ‘Advantages and Disadvantages of Client Side Seriptng... 2.1.3 _Diflerences between Client Side aid Server Side Scripting Language. 2.1.4 Using JavaScript in an HTML Document 2.45 JavaScript Example 22 Programming Fundamentals of JavaScret: Vaables, Operators. 224 Variables, 222 Operators.. 23° Control Flow Statement. nnn 234 Conditional Statements. 2.3.2 Loop Statements... 24 25 2.5.1 Function Defion .. 25.2 Defining Function Arguments... "2.5.3 ~ Defining a Retum Statement. 26 JavaScrist Objects. 2.64 Creating Objects in JavaScr 262 263° 264 27 28 29 | aber 2.1} Crcepten Hening in JavaScript 2.66 Numbor Object. 287 Anay Object... Browser Objects - Window, Navigator, History, Location, Document. 2.7.1 Window Object. 2.7.2 Navigator Object. 27.3 History Object. 2.7.4 Location Object.. Document Object Model 281 DOMLevels 2.82 Properties and Methods of Document Object... 2.8.3 Manipulation using DOM. Events Handling. 214 2.13.1 Syntax Rules. 2.192 JSON Data Types. 2.133 JSON Object. 2.134 JSON Function Files 2.135 JSON Http Request... 2.138 “JSON SQL tiple Choles Questions Chapter Ends... (New Syllabus wef academic year 21-22) (MS-67) jech-Neo Publications...A SACHIN SHAH Venture JavaScript is. light-weight object-oriented programming language which is used by several websites for scripting the webpages, '* TavaScript was developed by Mr. Brendan Bich in 1995 who ‘was working in Netscape, © JavaScript is not a compiled language, but it is a translated language. ‘* The JavaScript Translator (embedded in the browser) is responsible for translating the JavaScript code for the web browser, © Iis an interpreted, fll fledged programming language that enables dynamic iterctvity on websites when applied tan HTML document. + SuvaSeript belps to make our webpage more lively and imeractve, JavaScript i widely wed in mobile application evelopment as well asin game development. + JavaScript was initially called as LiveScript and later on the ‘ame is changed to JavaScript. + With JavaScript, users can build modem web application’ to interact directly withot reloading the page every tine. Te ‘traditional website uses js to provide several forms of inc asin, © Features of JavaScript ‘The features of JaVaSctipt atts follows: 1. ‘All'popular web browsers support JavaScript as they provide bailt-in execution environments. ‘2 SavaScript follows the syntax and structure of the C programming language. Thus, it isa structured programming language. 3, JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation), 4. IavaScript is an object-oriented programsiing. language that uses prototypes rather than using classes fr inheritance, Itis a light-weighted and interpreted language. 6, Ihisacaso-densitive language: * JavaScript is supportable in several operating systems including Windows, mscOS, etc, Itprovides good contro! fo the users over the web browses (Front End Development) ..Page no. (2-8) ‘ra Applications of JavaSerint ayaSctip s used to create Interactive websites. It's mainly . | Wed for: "+ Clentsdevaitation, + Dynamie drop-down menus, Displaying date and ine, + Displaying popup windows and dialog boxe ike an eet dialog box, oni dialog box an prompt sg bon), Displaying eloes, te. 24st Characteristles or Advantages of JavaScript si DOLLA OAS LELEL ES fee Gpanceeisiesepe 2! al * © JavaScript is a lightweight, interpreted client-side scripting language: # ‘© Designed for developing network-based applications ‘© avaScriptis complementary to and integrated with HTML. «enti ‘e ) cThis'user input is-validated before sending the page to the ‘server. This minimizes the server traffic, which tends to fewer Toads on the server. oe ene ee ero ae ome been forgoteato eater. . © Interactive interfaces.can be ‘created, which can give sopie bleo ees Ke mean bt activities. + Tai cine danse dg ri and sliders to provide a feel of rich interface to the users. 24.2 Advantages and Disadvantages of Cent Side Scripting ik Me Lj © Advantages 1 Iumeiate spon toa wie’ actions, whch ensbles more wes patie 2, No need to go tothe setver hence, execution i fast. 3 Improve the usability of we sits for users whote browsers suppor scrips. (New Syllabus w.e.f academic year 21-22) (MS-67) (Bltech-neo Publications.:A SACHIN SHAH Venture kL (Front End Dovelopment)...Page no. (2-4) {ntomet Programming (MU - Sem 5 - Comp.) 4. Dev h - | te Famers peer r ce ‘control over the look and behaviour of server Side Scripting Language! 5. Possible to subsite by HTML if user's browsers do not i support srg Tock | User ean block the | User cannot lok the 16 Are teuuable sad chttnable from vacoos (ypes of fe Cent side seriptng | Server side scripting oercan guage langue " Disadvantages Rese | Response from clieaeside srt 8 1. Seips are not supported by all of the browser; hence errs nik since te serps | slow sine he srs might occur ino altematives have been provided re processed.on the | are processed on the 2. There is need of more quality assurance testing as different eal comp revi comee browsers and browser versions suppor scrips differently, Examples | JavaScript, VBScript | PHP, JSP, ASP, 3. May need mor time and effort for development ifthe scrips ce LEE pb ‘are not already available through other resources. = 4. Sometimes, the web widget looks like cont , ‘ re astandard contol but | 23. 2.4.4" Using JavaScript in an HTML their behaviour may be different or vice-versa, which may lead to usability problems. WS 2.1.3 Differences between Client Side and Server Side Scripting Language {GQ What ate Gierences between ats aie “The server side script is executed by the ‘The client side script is executed by web ‘browser which is Jocated at the user's computer. Web Server. that outputs the page ‘which is to be sent to the browser. ‘Server side scripting Tanguage can connect and access (0 the databases which is located on the web server. ‘Server side scripting Tanguage has acess to the filesystem which is Iscated on the web server. Cleat side scripting language cannot connect tothe . databases which is located of the web serve ‘Glent side scripting language cannot have access to the. file system which is located on the web sere Gliet. side scripting language can access the files and settings that are local at the user's computer. File System Server side scripting language cannot access the stings that belong to web server, ‘Access to Setting (New Syllabus wef academic year: 21-2) (M5-67) Document + The code (cit of JavaScript is writen in the sript opening and closing HTML tags in a web page Usual, the ea se ® Calling a function on click event of a button ton tcl the function

(New Syllabus wef academic year 21-22) (MS-67) {Front End Dovelopment...Paga no. (2-18) Sons a a j SMounil> ae 5) %® 25.2 Defining Function Arguments While defining a foretion, we can declare variables in the ‘header statement of the function. These variables are known as ‘Parameters or formal arguments. When this foction ges called, we can pass values for these variables. These values are known as arguments or actual arguments. —varsum =a +b; 2 - a Tech-Neo Publications...A SACHIN SHAH Venture cikthe lowing baton to mane a a YW LSI Defining a Return Statement TGQ. Wes program which wil cept to numbers #1 {2 arguments and retustheisummation. vaSeript"> varsum = a+b; ‘In JavaSerpt fonction we can have rtum statement which is optional. This helps to etum a value from a function. This statement is written atthe last in a function. ‘The returned value goes tothe location wher the fonction is (Front End Developrent)....Page 10- (2-19) yas) savascnir onrecrs VQ. That are Javascript objec Ut the important bu ra in object How can you wile your own objec cown state and ‘An object is nothing but an catty having ‘behaviour (properties and methoxs). For example : A flower is an object having properties lke colo, fragrance ete. Other exams of objets ae ca, PE™ Module bike, char glass, keyboard, monitorete. JavaScript is an objec-rened language. Everything in JavaScript is considered as an object. Examples of object Flowing are some ofthe examples of objects in JavaScript. (Booleans i) Numbers (ii) Stings (iv) Dates (W) Regularexpressions (vi) Amays (vii) Funetions ‘Wecan create our own user defined objets in JavaScript JavaScript is primarily a template-baed scripting language rather than a class-based language, Hence, we directly create the object witht class, YS. 2.6.1 Creating Objects in JavaScript A. JavaSeript Object by Object Literal = Stax eel ise mt of eng si ject Literal: (New Syllabus wees academic year 21-22) (M5-67) [etech-teo Publications ASACHIN SHAH Venture Intomet Programming (MU- Sem 5- Com.) ncript language "JvaSetipt”> ‘employee = {id:101,name:” Prajohia Lonkar™salnry:t000) document wtite(employeeid-+""+employce:names"." ‘employee salary): (Front End Developmeni)..Page no (2-20) Bloom ars CG carmnbentntegt ripeparranod 18-Chetana Murvskar-800000 leript> SIloot> , 3. My usingan object constructor . ‘sfhuml> © Mere, we have to create parameterized fanctic ~ Orpet eywod is ed 1 asin cach argent sale inthe cue - object. 2 ~ eens | f Tertibewon estos cont bes 29-Prajakta Lonkar-40000 © Program using “this” keyword 2 By eating instance of object ‘ © symeax Objects <hitle> Following isthe syntax of erating instanceof object: Beak ‘var objectname=new Object(); sae Here, new keyword is used to create objet. Se a. © program of creating the instance of object | <script langusgo="JavaSerip” > eee function student(dsnameynatks) <head> t i feite>s thissname=sname; Objects this.marks=marks; <hitle> Ve efhead> = new student(20,"Gaur t document rite(sid-+” = "+s-sname+” ~"+smatks}; ‘<script language="JeveSeript"> ‘yar employee=new Object(); ‘employe salary = 00000; a 4 Lwrite(employee.id-+”-"-+employeename+”-*, (New Syllabus wef academic year 21-22) (MS-67) </script> </font> ‘<hbody> ‘shui Output 2.6.2 String Object ‘The JavaScript Sting objec isa global object hat is used to store strings. A string is a sequence of lentes, numbers, special characters and arithmetic values or combination fall, Brech-neo Publications... SACHIN SHAH Venture ntemet Programming (MU - Sem § - Comp.) ea Syntax (plead = Hew Singtel: “The String parameters series of characters that as been properly encoded @ Sering Methods Here isa list ofthe methods available in String object along with their description. (Front End Development)..Page no. (2-21) Sr.No. }) Method Desetlption : 1._| charary Reums the character atthe specified index. Module 2._| eharCodeato Retums the Unicode ofthe characte atthe specified index. ry (io cr loosen we 4._| enaswino ‘Checks whethera sing ends wit a specified substring 5. | fromCharCodeO | Converts Unicode valves to characters [5 [sae | etree el ig 7._| indexof0 Ret the index of the fst occurence ofthe specified value in a string. 8,_| tastndexo1) Returns the index of te last cccurrence ofthe specified value in asing. 9. | localComparet) | Compares two strings inthe current locale 10. | matcho Matches a string again regular expression and retums an array of all matches. 11, | repeat) Reruns a new string which contain the specified numberof copies ofthe orginal suing. 12. | replace, Replaces the occurences ofa string of paltem inside a string with another sting and return al new string without modifying the original string, 13,_| search Searches a sting aginst regular expression, and returns the index of the frst match 14,_| sticed Extracts a portion of suing and returns its anew sting, || 15. | sptito Splits a string into an aay of substrings. 16, _| statswitho Checks whether sting begins with specified substring. 17._| substi) Extracts the part of sing between the stat index anda number of characters aftr. [18._| substring Extracts the part of asring between the start and end indexes, 19. | toLocaleLowerCase() | Converts a string to lowercase letters, according to host machine's current locale, [20 [rarecsevepercaed | Comers stig pees eters scog os mtn’ curentoe 21. | toLowercaseq _| Converts a string to loverease letters. 22._| Sting) Retums a string represeating the specified object. ! 23,_| toUppercased Convers astingtoupperas eters. | 24. | timo Removes whitespace from both ends of a string. | [25.__| vatueoro Returns the primitive value of a String object. (New Syllabus w.e.f academic year 21-22) (MS-67) [eal tech-Neo Publications..A SACHIN SHAH Venture latemet| (4U- Som 5 26.3 RegExp Object + RepPep object ase to vide the pattern of characters © Rephp define methods hat owe repur expresciont ty Terform perwerfl patie matching Md earch and place Fonction on tert + Repu expressions canbe defined by esing following ways © Using Reg) Constr: var RepulaEpresson « ew RepEnp pers, ag”); © Using Literal va Reglatxpression = pate Mag © Pane — A String tht specifies the pater of the repular expression or another regular expression (© Flag - An optional string containing any of the " and “in” atrbues tht specify global, eaveinsensitive and rultiple matches respectively. ‘ Properties of RegExp object 1. Constructor « Returns the fonction that ected the RepEtp object 2 Global - Checks whether the "e* modifier is set nnoreCase - Checks whether the “i” modifier is set any tring ercloned within cho ted co matches any string containing ap folie by zero oe more instance ofthe enrence by —E—E~_E % 2.6.4 Math Object The Math object is sed to perform simple snd complet arithmetic operations The Math object provides 4 tumber of properties and methods to work with number vale $ The Math object does not have any conctructors Al f its ‘methods and properties are static: that i, they are member functions of the Math object self. There is no way eeate ‘an instance ofthe Math object. © Syntax var piyal = Math Pt; l= Mat ‘'F Math Methods (30); Following are some important methods of Math Object 4. lastndex + Specifies the index at which to start the next | | Method. Dest a abs0__| Returns the absolute value of a number. ‘S. mutline - Checks whether the “m" modifiers set ceil). | Reruns the smallest iteger greater than o equal © 6 source - Returns the text ofthe RegExp pattem. number. "@ Methods of RegExp object exp0 Retums EN, where N is the argument, and E is Euler's constant, the base of the natural logaritim, 1. exec()- Tests fora match in a sting. Returns the first match. oor cts the largest integer less than or equal to 2 tet) Tests fora match in asin. Rens tue false. 1) | Os onl 3. toString - Returns the string value of the regular , * TT gd | Reruns the natura foparhm (base Eo unter expression. 4. tSource() - Returns an object literal representing the || max} Returns the largest of ero or more number. specified object. mind __| Returns the smallest of zero or more numbers. Foie examples explsie ma sboet msthing SUA Pow) | Returns base to the exponent power, that is, base Expression | Description exponent. . {24-2} _| It matches any string not containing any of the random() |. Returns a pseudo-random number between 0 and I characters ranging from a through and A through Zz round) | Returns the value of a number rounded to the a integer, PP ‘tmatches any string containing p followed by any nearest integer. character, in tum followed by anoterp sqrt] Returns the square rot ofa number. ‘A(2}$ | Stmatches any string containing exactly two characters. (New Syllabus w.e.f academic year 21-22) (M5-67) Tech-Neo Publications..A SACHIN SHAH Venture Intemot Programming (MU Som 5 - Comp.) {Front End Dovelopment)..Paga.na. (2-23) 8] properties of Number object WLS Date Object At times when wser nod to aces the current date and tine an also past and future date and times, Java provides support for working with dates and tine throug the Date object. 4 The Date object provides a spten-independent station of dates and times, Date object cane created as: var today = new Dale 4 Dates may be constructed from a year, month, dy ofthe rmocth, hour, minute, and second, and those six component, aswell asthe day ofthe week, may be extracted fom ade. + Dates may also be compared and converted to #rexdsble string form, A Date is represented to a precision of one rillisecond. © Properties of Date object 1. Constructor - Returns the function that crested the Date object. 2. Prototype - Add properties and methods to an objet © Methods of Date object 1, Date()- Retums today's date and time 2. getDateQ) - Retums the day of the month forthe spcitid due getDay()- Returns the day ofthe week forthe specified ate getFull¥ear() -Retuns the yer of the specified te gelHfours0 - Returns the hour inthe specified da acceding to local time. getMilliseconds() - Return the milliseconds inthe specified ate according to local ime 6. getMinuteO, getMonthd, geTimed, getTimeronetet0, setDate), setullYearQ, setfloursQ,_setNllstcondsQ, setMinutes), setMonth0,setSeconds()se(Time) ar some ofthe methods used in Date objet 2.6.6 Number Object The Number object represents aumercal dat, ier integers floating post umbers. ‘+ ANumber objets are created using the number coastuctor ‘yar num =new number(value; a 4 2) Constructor « Returns the funtion that created the Number objet. [MAX VALUE - Returns maximum numerical value posible In avert [MIN VALUE - Returns minimum numerical value posible In JavaScript NEGATIVE INFINITY - Represent he we of neative oq) infty. ry [POSKTIVE INFINITY - Represent the value of infinity. Prototype - Add properties and methods oan object Methods of Number object toBxponentlal) = Convens a number ito exponential notation AoFixed) - Formats a number with a specific number of gis tote ight ofthe decimal toLecalString() ~ Retuns a string vabe veson of the cent number in forat that may vary according t0 a browsers locale seings. toPrecsion0 = Defies how many tou digs to display of umber. {oStrng() - Returns the sting representation ofthe umber’s vale. ‘ale Of) -Retusthe number vale. 2.6.7 Array Object “Motiple values are stored ina single able wig the Array object. In avaSeip an ary can ol feet ps of datatypes, ‘which implies tat nara can have a stag a number or an objctina ingle slot ‘An Aa abject can be crested by using flowing ways: Using the Array Constructor ‘To rele empty aay when don't know the exact number of elements tobe inserted in an aay (New Syllabus w.ef academic year 21-22) (MS-67) [drech-ieo Publications .A SACHIN SHAH Venture Internet Programming (MU - Sem 5 - Comp) (Front End Development..Page no. (2-24) ‘Tocreatean ara ih given lees r= ara Property” Z Description “| jp |] ase returns a boolean valu that specifies wheter | ~ Using the Array Literal Notation: ee _A window has been clased of not ‘To cresteemply array Default Status | specifies the default message that fas to be Farahjaame = : appeared in the statusbar of a window “Tocrete marry when clement ar von document __| specifies a document objet nthe window Vat arrayname =[“element nreeneh 2 AL Aretement hs || frames specifies an array of all the frames in the an); : current window © properties of the Array object bistory specifies ahistry object forthe window an fa window's 1. Length Retums the number of elements in the ara. Inver teght specifies the inner tele o ° 7 eae contentarea 2 Constructor « Returns the function that created the Array oe on Tmnee Width | specifies the inner wish of window's coment area 3, Proltype- Add properties and methods to an obec. en a eogth species the umber of ras conned EF Methods of the Array object es 1. reverse) - Reverses the array elements peifes a location object forthe window 2. coment) -Joins two or more mays ' Methods of window object 3. sort) -Sorthe elements of an ray ‘The important methods of window object at a fOUOS 4. push0 - Appends one or more elements tthe end ofan array’ ||" sfethods Reon 5. pop()-Removes and returns the last element alert) displays the alert box containing message with 6. shift) -Removes and returns the ist element ok button. 7. unshitQ, join), indexO10, lastindexOf0, slcestartindex, enfin) | displays the confirm dialog box containing cendindes) are some ofthe methods used in Amay object. message with ok and cancel button. romp) _| displays a dialog box to get input from the wer Droz. BROWSER OBJECTS - WINDOW, jemi NAVIGATOR, HISTORY, LOCATION, | | :72%0___| ovens the nev wink i close) closes the current window. seéTimeout() | performs action after specified time like calling Following are some important browser objects provided by function, evaluating expressions etc. JavaScript: % 2.7.2 Navigator Object Ww LIA Window Object ro + The JavaScript navigator object is used for browser ‘The window object represents a window in browser, An object of window is created automatically bythe browser. ‘e_ JavaScript Window Object Properties detection, It can be used to get browser information such ss appName, appCodeName, userAgent etc. ‘The navigator object is the window property, so it can be accessed by: (New Syllabus we. academic year 21-22) (MS-67) [Blrech-Neo Publstions. SACHIN SHAH Vertue (Front End Development)...Page ro. (2-25) ~ jnigmat Programming (MU - Som § - Comp.) # JavaScript Navigator Object Properties Output Property Descripiton JavaScript Navigator Object sppsdename specifeste codename oft browet |) aa, spare specifies the name of the browser ris Siena linn 710, a Alea 7250300. the Saipan ao Sa depversion specifies the version ofthe browser Zaeweues being used So See sqrt 0 ttt Apes Hobe asa Gee oF cookicenabled specifies whether the cookies are somaaden Volt «enabled or notin the browser platform contains sting indicating the 2.7.3 History Object machine type fo whch the browser " es vas compiled 1 GQ. What's the purpose of Hitory browser objet in wegen ‘contin a suing representing the value | |. JavaScript ? Explain its any two methods. 1 of the user-agent header sent by the 7 arcs oa oe aaa a lint inthe hp proccol |} * THe JavaScript history ob ns an arya fest fore sererin te i visited by the user, By using this object, you can load ' Methods of JavaScript navigator object Following ae important methods navigator objet: Method Deserption juvaGnaled() | checksifjavais enable tainténabled() | checks if taint i enable. It is deprecated since JavaScript L2 Example ‘chum ‘<baiy> “<h2> JavaScript Navigator Object </h2> sserpt> Mocument.wrteln("<br/>navigaior.ppCodeName: ‘navigator. appCodeName); ocumentriteln("'<br/> navigator.appName: / +avigatorapp Name); document. writeln(” <be/> navigator appVersic +navigator.appVersion); ocumentwriteln("<br/>navigator.cookieEnabled: * + nnvgator.cookieEnable) document. writeln(*<be!>navigator language: 4 naignor language): secumentriteln(" </> navigatoruserAgent Poni document. writela(" <br/> navigator platform: 4 navigator platform); tor.userAgent); previous, forward or any arcu page. The history object is the window propery, soit ean be accessed by: ‘window history oR history © Properties of JavaScript history object Property. Description Length specifies the number of elements contained in the object Cureat specifies the URL of the cureat entry inthe object Next specifies the URL of the next ekment inthe History list previous specifies the URL of the pevious element in the History ist |F Methods of JavaScript history object ‘There are only 3 methods of history object. Method Description forward) loads the next page. back) Toads the previous page. 20) Joads the given page nurer. Example sment.writeln(" <br/> navigator.onLine: Pi ariguoronLine); histo forward nex page oe ‘istory-g0(2);/ffor next 2nd page Ue bina g2)ifoc revi 2nd page (New Syllabus w.e, academic year 21-22) (M5-67) Ll reeh-Neo Pubcations.A SACHIN SHAH Venture Jetemet Programming (MU ~ Sem 5 Comp.) (Front End Development...Page no. (2-26) penne ' ere GQ. Whats the purpose of Location browser objects in JavaScript Explain ts methods. + The location object in JavaScript helps in storing the information of eurent URL of the window objet tsa chil object of the window objet + _Thetahe given below describes the properties af the Location objet aaSerip. Property. Description Example Tet | represents a string specifying the entire URL itp PhoenixGlobe com A0MuestaspTid= estat protocol. | represents a string at the beginning of a URL up to the first colon (3, | http: or hips: which specifies the method of access to the URL ost | repens sting consisting of the hostname and pot sings FhoenixGobecom60 Tesmame | rein the server mame subdomain, nd donsin ame of URL. | PhoenxGlob-com Port ‘represents a string specifying the communications port that the server uses_| 80 pathname | represen a sing portion of URL speciing how a parc sauce | testasp canbe acessed search| repeats a ing bepnning witha question mark hat spe ay gory infra in an HTTP URL Tash | represents sing beginning with a serfs an anchor rane in an | stat HITPURL Location Object Methods Patimamefldalus “The following ble ists the methods ofthe Loeaon object Se : interact sleaiot> aE ‘</head> © Method | apes assign() Loads a new document in the browser “<h3>Enter URL in following sections </h3> reload) reloads the current document that is contained inthe cation href propery coment with the || <* replace) | poces, the creat” document ption>hitpl/<Joption> <2 = a Speed new one, you can not navigate back | | ;<ention>tp/ <font tothe previous document using the browsers | | ‘<eption>file/<Joption> 6 Back button “<option>javaseript: </option> ‘<option >fip:/</option>~ ‘<option>mailto:</option> <felect> See (New Syllabus wef academic year 21-22) (M5-67) ‘Tech-Neo Publications. SACHIN SHAH Venture Paine it ype= tea re =D" manengh® "100" ares athnameF 1 vie="7> eR <tr <n 1 ing ype="baton” name="Ga" vle= eich="puol "> ler © feyjicrsmt.nont > 04 Enter URL in following sections Protocol: trtomet Programming (MU - Sem 5 = Comp) (Front End Dovolopmant)....Paga no. (2-27) Any element of IITML. page can be acceee byw phe Mhocument objet ‘Acconting to WSC(World Wide Web Convo) “The WIC Document Object Model (DOM) i platform and language reutal interface tat allows programs and scripts to dymamisly “| secess and update the content, structure, and style of document.” 'T Hierarchy of objects In web document Document Object Model (DOM) is the metho by which he content of documents accesel and modified. Ina weh document, the organization of ebjeets is implemented in irachial sinctu. % 2.8.1 DOM Levels ‘The DOM provides JavaScript with ll of the fears itteeds to generate dynamic HTML: Changes can be made in all HTML elements. ‘The eae buml documeat is represented by the documest jet. ‘The band document becomes document cbject when itis ended in the browser. The rot element represents the inl ocumeat. The document object as popes and metho ‘Tae documeat object helps to add content dynamically inte rate Changes cnbe mein es of TL eet sostuas! Changs canbe main CSS sys inthe age. [PhoesixGiobe.com ‘+ Existing HTML elements and attributes can be deleted. dane: «New HTML leents nd aur can beste a ‘+ Response can be given to HTML events. Go, 4 NewETTL evenscanbe cet in TM pe SG wan _ __ Erne [iraort set paizi8 DOCUMENT OBJECT MODEL a ee! Te] ee] [oa —_— fu Fado] | [oa ‘© DOM stands for Document Objet Model, [Pesscon Flg.2811 : DOM levels web pe (New jlabus wef academic year 21-22) (M5-67) [Bb rech-teoPubcations.A SACHIN SHAH Vertue Modal k 2 4 sctemet Programming (MU: Som8 = Comp) YS 2.8.2 Propertles and Methods of Document Object ‘The contents of document can be accessed and modified with the help of methods, ee Method I Properties Description Value Retums value of specified textfield write(string?) Weites the specified string in the document, WritelaC string") Writes the specified sting inthe document with ‘newline character atthe end. J {Front End Davelopment)..Page no. (2-28) "orm |*> Ener Your Name: <input type= input type="bnton" onClick="callMe(;" value="Click Mere"/> </form> </font> <fody> <ftml> "Explanation ere, document represents the html document. Ii the root clement, © formt - rane of the form, * txtname -atvibute ame ofthe input text * Value - prope, that returns the valu of the input text. feiElemenB 149 Returns th element or having the specified id wee 7] valve, 0] 0 ow x ee fetElementsByNamet) | Returns all the elements CO Fle | CArsew/AdninDedeoptiameletztent having the specified name value. |Enter Your Name{saama ____}[ Ghee setElementsByTapNane)_ | Returns all he cements having the specified tag - name, Bom > PEigaeacems ‘betElementsByClassName() Returns all the elements. saceal = ‘having the specified class Eater Your Names raven name. meen = 1 Accessing field value by document object > Program 2.8.4 : Program of document object which accesses value from tet feld [ebin> ‘<head> Ktitle> DOM hitle> : cs |Secriptlanguage="JavaScript"> i Tunction callMe() £ var sname=document form] tname.vabies ‘lert’Weleome: *+snam); 2. write(“string”) method * This method is used to write output stream. © The wite() method is used to writes HTML expressions or JavaScript nfo a document © Displaying the message using write("string") method <html> <head> <title> ‘Write Method </ile> </head> ‘<body> ‘ <script language="JavaScript"> * document wile <b> This message is printed by write) method </b>} Tal tech-\eoPublcations.& SACHIN SHAH Venture jones © O tier scyprnent ‘This message is printed by write) method 3, writeln("String”) method ‘© Thismethodis used to write output stream, © ttlad adda new line after each statement, > Program 2.8.2 : Program to demonstrate the use of wetting”) method <!DOCTYPE html> <html> SONS. <body> <font ste=5> <p>Nole: write() does not add a new Line after each statenest<Ip> “<pre> “Kteript> ocumest.mite( First Line’), ocumentsrte(. Also onthe First Line”); ‘checigt> : ‘</pre> ‘<p> Note: writeln0 add a new lie after each ‘statement:</p> pe scip> ‘Bocuiment writeln( ‘First Line"); pent. writeln("Second Line"); fSlseripe> i Ecipe> Be Newel) ot aa pe ie each tte: rire Une. alo onthe Fest Le eta a dd new ine afer ech statement Feet ise Sane Une (Front End Development...Page no (2-28) document.getElementById() method ‘This method returns the element of specified id : © Symtax document getElementByl Inthe above script, we have used document form name ae fo access the value of text field. For the same purpose now we will use Daeument getElement) met Here we have fice id forte input text fel —e—e > program 2.8.3: Program to display cube of number sing Document.getEiementByld() method <<hunl> ‘ <head> <ile> Dow <file> <cipt language "JarSerpt'> furatoncube() { varo0 = document getElementBy14( num) values ales(oo%n0*n); } <beript> input type="text” um" /> <br> <br/> <input type "button" vlue="Display Cube" eaCick="cube()"/> <fomn> <<teat> } | (New Syabus wef academic year 21-22) (M5-67) I f Bh rech-Neo PblcatonsA SACHIN SHAH Vestue !ntemet Programming (MU - Sem 5 = Comp.) __(Font End Developmen)..Page no (230) 5. document.getElementsByName() method ‘This method retums all he elements of given name "© Syntax HoimehgelBiemcnisliyNamet Haine) Tn this example, we wil coun total number of languages Here, we are using getElementsByName() method to get all the languages, > Program 2.8.4 : Program to display number of lenguages ar thet cont on lek evento button ‘<himl> fetes 6. document.getélementsByTagName() Stites method Dow Alle elements of specified tag are retuned by this meta Shitle> 03] © symax ee ‘Sseript type="textjavascript"> <> | ocument getBiementsByTagName("tag_name’) ii i function languages() | > Program 2.8.5: Program to count total number of { 1 tags. used by document.getélementsByTagHeme() method ar lan = document.getElementsByName("lang"); rere a . ~ ‘alert(Total Languages:"+lan length); a oa 2 + ‘Stitle> Hy ‘</script> DOM oe <script ype="tenjavescript"> Be function ety). je Re lence“ G ‘var ot ~ document geElementsByTogName("); ‘Sform> alet(total p tags are:"entlength);. [eb rech-neo Publications... SACHIN SHAH Venture (New Syllabus w.ef academic year 21-22) (MS-67) trot Programing (MU - Som 5 - Comp) ee teenies Eamon aaa Thi Fiot Pare Eee Tepe) eed is used to cout eueney ofp jt Haven Lock as ‘<p>Click the button to eh Sirt div element with the ‘<button onclick="changeColor()*> Click Here</button> - <ectip lngiage="JavaScript"> funetion changeColor() { locument.getElémentsByClassNamie(Test Col x(0style-backgroundColor = "gray"; } <jerip> </font> ‘</body> <</himl> Output 7, document.getElementsByClassName() Be This method ums ast of al the elements ofthe document | with the given class name, as a NodeList object. cesarean + evan en | | nodes are accessed using index numbers which stats from 0. Frevnteeraiercerane: | > Program 2.86 : Program to demonstrate the use of | |e artmcdugrar tcl clare dr slene wie tor Cla” getElementsbyClassName( ) method FADOCTYPE bini> g kehml> ue ‘chead> i <style> : ce fice e Using avaript we can add or remove nodes (HTML border: 2px solid gray; ‘elements) inthe document. inden is 0.</p> ‘<jaiv> (cdiv lass ="TetClo> {-<p>P isthe element in first div with (A) Creating New HTML Elements (Nodes) Tnially we have to create the element (element node) which can be then appended tothe existing element. > Program 2.8.7 : toanexiing ‘sbiml> ‘<head> <iile> " ‘DOM Manipulation = ‘

,

It's not that Pm soxme, its jut hat Tsay with |pblems loge, Bees icpid="p2"> Albert Eins eee Nel Pie Wines rogram to append the new element + (New Syllabus wef academic year 21-22) (M5-67) fech-Neo Publications_A SACHIN SHAH Venture (Front End Developmen))....Page no. (2-32) Intemot Programming (MU Sem - Comp) ‘Sseript> ‘Yar prg = document.createElement(‘p’); ‘Yarnd = decument.createTeaiNede(‘A new Paragraph); PreAppendChild(nd)s Yar element = document getElement fyla(¥iv?"); ‘lementappendChila(pr; ‘Slscript> "© Explanation Ler’s see the cae Yar prg = document ereateBlement('p"); ‘A new

element is erated Nar nd = document.createTexNode(A new paragraph); A text node is created and testis added to element var element = document getElementByld(ivl); “This code finds an existing element: ‘elementappendChild(pra); t This code appends the new element to an existing element. Output ts oot hat Tin wo st, i jt aay it problems eg ‘Alber Ezsin: Theoretical Pics, Plorpher, Nobel Pize Winer Anew Paap (B) Creating new HTML Elements - insertBefore() In the previous program, we have seen the appendChild() method which appends the element atthe end in part, ‘The inserBefore() method is used to add the new element st panera > Program 2.8.8 : Program to add new element at the beginning using insertBefore() method a ea (New Syllabus wee. academic year 21-22) (MS-67) DOM Manipulation ‘

I ot that Um so smal i's jst that I say with problems longer. Albert Einstein: Theoretical Physicist, Philosopher, Nobel Prite Winner

varprg = documentereateElement(; tard = documentereteTentNorle("A new Pacsgraph.’); praappenddChildfed; var clement = document. getElement Bylo!) var child = docurenigeElementByld( pI" lementinsertefore(prg, child), , Output rere (Comer Ace Pang. estat som yet at sty wih probles es. ‘Abt Ena: Thee Poss, Pbsopber, Nobel Pie Winer (C) Removing Existing HTML Elements To, remove an HTML element, we should have the information aboot te pareat element. The removeChild() method is used to remove the HTML element, > Program 2.8.9 : Program to remove an existing [alrech-NeoPubcations.A SACHIN SHAH Venture | lntemet Programming (MU - Sem 5 - Comp) ‘eeerpi> srarparent = document getElementByld(vi"), frar child © document getElementByld('p1"}; emoreChildcil), l |ehey> | shunt Abert Est: Theresa Physi Phlosopex Nobel Pre Wane (D) Replacing HTML Elements [Kis also possible to replce an existing element by new one, ‘Tre replaceChil) method is used for this purpose, re > Program rogram to replace an existing element by new element using replaceCild() method ‘ DOM Manipulation ‘Siile> livd"> <IC3 not that 'm so sar, it's js that I tay vith, problems longer. 'p2"> Albert Einstein : Theoretical Physicist, Philosopher, Nobel Prize Winner

isiain> lesen - ar prg = document ceateElement("p"); rnd = documentreteTextNode("Replaced Dsia.); sopendChiad; ar parent = document gtElementByld( ‘die child = document getBlementByldCp1"; -33) (Fron End Dovlopmon).Page 0. (2 4 Output €) © seep Reged Da ‘Mbt ac: Terese Pysct, Poa, Nobo Pie Wie —a— 12.9 EVENT/HANDLING 2 "GQ api he event handling in laveScipt wth simple 4 le + Evens ae the actions perfonned by the end users while browsing the website. For example mouse move oF mouse lic onthe buttons. | * When an event is fired, objects are wiggeed which are associated with that specific event The evetis caught by the event handles and in response the related coe is executed ‘+ Bventsa basically classified in four categories: Classification of events, 1. Window events 2. Mouse events 3. Keyboard events 4. Form events Fig. 29.1 : Classification of events > 1. Window Events ‘Ther ar various types of events associated with window : onload - triggered when anew page is stating up. 1) oaUnload triggers when a page is shutting down, (ii) onResie - triggers when a page is resized, (iv) onMove- tiggers when a page is moved. (¥)_onAbort- triggers when apage is cancelled, (Gi) onFrror- triggers when an errr occurs. (i) onFocus - triggers when the: window moves to foreground, (vii onBlar- triggers when window changes to background. Tech-Neo Publications..A SACHIN SHAH Venture ntemet Programming (MU - Som 5. } 2 Mouse Events “Tere are yon types of events asecisted with mone: 1) omMoasedown «riggers when moase button is pressed ‘onan element i) onMoaseup iggers when moose etton i eens (iy onMfonsemave «tripe: when monte pointer ie moved and We pine is already over an clement (0) Men wien wer moe ie Ue uso down and mouse up events (9) onMouscorer triggers when the pointer is over an | > Program 2.9.2 : Program illustrating mouse up and clement mouse down events fehimi> ise? ae ‘chi |="myid 1" onmousedown="fun()” ¥ (vi) onClick - triggers when mouse button is clicked once. (vii) onDblclick - triggers when mouse button is clicked mee b he wat! Click the text! aK vets reutap="ind"> Gk eet cee \eeerin> There are various 1785 of events associated with | function funl() Aeytoad in @onKeydown- Triggers wbenakeyisprssed down. | | document. getElementBild( mid" style col (ooKeyup- Tigger: when key it led } (Gi) onKeypress - Triggers vhen complete key sequence, | function fun2() down pres and up release apes s > 4 Formevents “There are following types of evens associated with form: ( oaReset - wigers when the reset button onthe fom s clicked @)onSubaat -tiggers when te submit buton is clicked. (Gi) onSclec - triggers when a contents selected on ape (A) Using Events ‘All these event can be used to cxtevte some scrips. In te |} following programs we will use mowover and mouseoutevens. | (Click the text! CO he| catenin > Program 29.1 : Program to tlustrate the use of 5 Programs > Program 2.9.3 : Wiite a program to show the use of events to change background color with DHTML. If ‘mouse button Is pressed, background color should be red, If mouse button is released up, background color should be yellow. dy stele back erand0stor ro yellow) | docurentbody style hock roandColor="yellon® Kcthead> ‘ected oadloaseDown="red);" onMousel Ketody> ketm> Onspat GB) D onemarancc xP CO Re | CtsevsdnivDesktopangle 2h yllon(h"> > Program 2.9.4 : Wrte using JavaScript how to know which mouse button wes dicked, number of elements in form, and write helo world. ‘rar


(New Sylabus w.e f academic year 21-22) (M5-67) (Bb rech-teoPbicatons A SACHIN HAH Venture Intomet Programming (MU - Som 5 -Comp) > Program 2.9.5 : Write JavaScript that handles folowing mouse event (2) mouse ten button pressed on browser it displayed message “Len clicked” (b) 1 mouse right button pressed on browser I displayed message "Right Clicked” *® JavaScript handling mouse events Title of the Page<ftitle> <Ihead> <body> “<script language="JonaSeript"> var sTeatEventType='mousedown's function handleMouseEvent() { arent ull? evente); var clickType = LEFT if (evtsype!=TestEventType) retum tru; if (extwhich) { if (evtwhich==3) clickType="RIGL } if{clickType == ‘LEFT) alert (Left button is he ilcickType alert(Right button i clicked"); return tue; , ‘document onmousedewn = handleMouseEvent; ‘documentonmouseup = handleMouseEvent; ‘documentonclick = handleMouseEvent; ‘slseript> ‘</body> |sfhiml>, : I {Front End Development ..Page no. (236) > Program 2.9.6 + If button named “red” Is cicke, background should change to red and If button named “green Is clicked, background should change tp green, <himl> shend> «title <script ipe="tentfjavascipt"> hanging background eolour fonction rel) { doe } function green) { document body.syle-backgroundColor="green™ } ut.ny.stylebackgroundColor="red” ‘ jon mpKeyPrese) fant | ft ‘ake fiwindonevert) (IE 4 enum = ekeyCodes i stfembich){ // NetseapefFirfovOpera {eynur = eohichs } yar cat] =StingfromCharCosle(keyrum) ioe vovel ich [| chart { Alea you have pressed vol) } alert(you pressed "tcharl +" & epee for that is "+ keynur)s } function changebgcalor) { document getElementByld('txt1') siplebackgroundColor = ‘blues J hhead> kehody> ‘ {etrn’> |] chark=="" |] charl==' || charl==6! ) | tree | memietmne > Program 2.9.8: Design HTHL form which include two fields usemame and password. Write JavaScript code ~ to show and hide password 'F JavaScript code to show and hide password (lunetion() { Module var Passwort Togler = funetion( element field) { y this.toggle ‘ PasswordTogeler prototype = { toggle: funtion) { var sell = this; i sell clenentaddBventListener{ "change", function() { if selflementchecked ) ( selfield.setAtsibute( "ype, "text" Dele { selfeld.setAtbute "ype password); } }, false); } b ce document adaBveilistener{ "DOMContentLoaded’, function) { ‘var checkbox = deeuoent.querySelector("#show-hide™), pnd = documentquerySelector( "pwd, form = document.querySelector( "#login" ); form.addEventListener{ “submit”, function e) { cepreventDefal() }, false); var togeler = new PasswordToggler( chechox, pwd) yo): DO: |< /Scrpt {elem action=" mand="pstid="logi'> | (New Syllabus w.es academic year 21-22) (M567) Bhrech-eoPubiations.A ‘SACHIN SHAH Venture Lntomot Programming (MU- Som 5 - Comp.) © Sfont sire=5>
Usernane: name" name="name” input type="password” id="pwd” name="pwd” *>Show password ‘Sifont> ;

‘ GO ie | ciseryadeinvdedeeptmelet2 html Usemame: ass} Password: Show password > Program 2.9.9 : Write a code in JavaScript to open a window when a link on a page Is clcked. The new window open is closed by placing a button on the window and writing JavaScript code on the onClick event of the button. (Front End Development..Page no. (2-38) f= "javasrit:openWin()">Open

Output © fesjietnemt 2.10 FORM VALIDATION USIN JAVASCRIPT E ‘JavaScript fom are the logis onsiner of all the contol (elements) Before submiting any form to sever, its very important 9 ‘heck the fom for its validity because it may possible tat user has missed some data or etred some inappropriate ata. Tt canbe done on sere side also. But if data is not agpropriate te it has to be edt client side for cometca which is a time consuming process. Hence JavaScge Provides client side data validation withthe help of forms. i makes the processing fast * Data validation is considered as « process of verifying tat {nut given by users clean, cont, and useful "© Validation tasks ‘Typical validation tasks ae as follows: © Whether all equired fields are given by use? ‘© Whether dat entered by users valid? Whether datatypes ofall values ar comet? (New Syllabus wes academic year 21-22) (MS-67) 3 Tech-Neo Publications_A SACHIN SHAH Venture ea Ae fe data a follows: The name should n Bea sword should not be les than 6 characte ' “ alect(Please enter name’); relum false; } ele ifpwlength<6) { alet(Password should be more tat 6 characters"); return false; ‘psubmit="retur chkDataQ;"> ‘loa site=6> ‘Ester Name: Sb b> are Pest
[cio “eubmit" value="Submit'> at > 5 | Pe - | ‘ ‘ ‘ function chkPass0) { ‘ar first = document. pss ral} ‘ar sezand = document.fim.pass2ealues Module, 2 ‘alert(‘Both Passwords should be same"); ‘etum se; } } “ceip> ‘ lchkPass("> ‘foot sice=6> ‘Eater Password Enter RollNumber:
Enter RolNumber: = ———Only Namerie values are allowed (Front End Dovelopment..Pagono. (2-40). 5 JavaScript email validation 1GQ. Accept emal-id caieria | Email must contain (dot) {rom user and check wth following , character ond 1 ‘ ‘ + @ symbol. There should be minimum 1 character {before and after the @. Tere soul be minimum | "3 JavaScript to check email validation s function emait_yalidateQ) indexO1(@'); var dotpos = eidlastlndexOI("); iF (xpos || doipos ‘ consubmi ‘ : at" name="txtemail">
.
Email: <3 ‘sihiml>. sine Output (New Syllabus wee academic year 21-22) (M5-67) [Bbrech.Neo Publiations..A SACHIN SHAH Venture | | | Fe pwvaseript mobile ancl emai validation Write down Javascript code to check mobile number y ble umber should stat with 9of-@) and all» Wick @ and) i , s& JavaScript. to check mobile and emall validation eit > Validating Mobil cecript ypo="tenljavaseript"> umber title fantion vaidate(mah) { var Mag = false; sarmiength = mob length; it(anoh.charAt(0)=='8" || mob charAuQ)==9) && riength==10) { fag=tmne; } if(ag==false) alest(Please enter valid mobile number) eke ‘alert(Thanks, data submited”); } 149, Wilo clown avn sc cto vallato user nly 4 ' + }4and password (password engtly must in between 6 4 1 (0.22 charactors, User nane should not start with 4 1) @,or any number, both are not blank), avin 1 JavaScript coda to valldata username password hotwoan specific fongth of charactors eal Moda funtion eld Datn(um,p) { itfomen= | pops) { lent("eas fil all date") J cls iffanscharAt(0)=="! | | nmchart(0)==4@ | | (umelirAn()>20! 88 nnd) <=) { alent(Plese enter vai nan } lag iffpwelength<6 | | pwlensth> 12) { slert(Password length shouldbe between 6 to 1 i character}; " che { alert("Data submitted"); } I iba> Passwort: (eu Sylabus w.ef academic year 21-22) (MS-67) 4 Tech-Neo Publications..A SACHIN SHAH Venture {ntermet Programming (MU -Sem 5 Comp.) Enter Password: = ‘ GQ. Design an login form vsing IML ond JoaSegt uy with following. validations on password. field; | minimum length & characters, It should have some * "© JavaScript code to validate 2 form with minimum password length 8 characters ‘ ‘ iid), Enter Email ID Eater Email ID as "ee 5m ' Es ‘© In programming, exception handling is a process or method used for handling the abnormal statements inthe code and executing them. I also enables to handle the flow control of the eadeprogram. For handling the cae, various handlers are used that process the exception and execu the code. (New Syllabus w.ef academic year 21-22) (M5-67) Tech-Neo Publications...A SACHIN SHAH Venture uomat Progamming (MU - Sem = Con) For example, the Division ofa non-rero wae with zero will it san exception, Thus, with the Help of exception handling, it can te executed and handled, In exception handling a throw statement i wed to raise an exception It means when an abnormal condition occurs, an exceptions thrown using throw keyword. ‘© The thrown exception is handled by wrapping the code into the try..catch block. If an eror is presen th etch block will execute, else only the try block sutements will get executed © Thus, in a programming language, there can be different types of eros which may disturb the proper execution ofthe Progra. 1 Types of Errors iil coding, there canbe te types of rin he ode: 4. Syntax Error : When a user makes a mist inthe pre- efned syntax ofa programming language, a stax eror say yea. 2 Runtime Error: When an erorocus dng the execution ofthe program, such a enor is known Runtime er, The cedes which create runtime erors are kzown as Exceptions. ‘Thus, exception handlers are used for handing runtime ers ‘4. Logical Error : An enor which occurs when there is any Topical mistake in te program that may oot produce the desired output, and may terminate aboorly. Such an eror is kaown as Logical enor. JavaScript provides eroc-handling mechanism 10 catch runtime ers using ty-catch-finaly bl, similar to other languages ike ava or Cf. (Front End Dovolopment)...Pag9 00 (2-43) Aryl) statement: The cone that requires eror testing I kept within the try lock. Hf an eto ocur, i 6 passed (0 the, cateh() Black, which takes appropte actions and handles the error, Otherwise, it runs the cofethat was written wii. block handles the erro ofthe ee ttements writen within the block the wer defied exception handler when any 4 eatch( slaterent : This by exccsing the set of “Ws block contains citer | ov the builtin han, Tis black executes only error-prone code needs ‘Otherwise, the catch block is skipped. 2 «Flay taement + Coe in he ally block wil alway be cexeeuted regress ofthe ozcuence ofan error. The ial took canbe used to complete the maining tsk OF eset vadable that might have changed before ror occured in Uy tock. ‘Example : Error Handling in JS _ . ‘BOCTYPE him > # g ‘. © ghL> Dem ior Handing Demo: Error Handling ReferenceError: Sum is not defined Brech-NcoPubcations.A SACHIN SHAH Vertue toe fant nthe ty Block. More

You might also like