JavaScript JQuery Jon Duckett
peach
n ee See ee em cee ee ere as ieee which elements) the Peete eee apples o, The declaration block (the aspect you want to contro, rien ee eee re cr ee RC selector andadeciaratonblock. those elements shouldappear. _forthat propery. aaa ahem clr Leet fa Sy rar tne)BROWSER SUPPORT Some early examples i this book do not work with Internet Explorer 8 and earlier (but alternative code samples that work in IE8 are available to download from http: //javascriptbook. com). We explain techniques for dealing with older browsers in later chapters. Each version ofa web browser adds new features, Often these new features make tasks easier, or are considered beter, than using older techniques But, wobsite vistors do not always keep up with the atest browser releases, so website developers cannot aay ely upon the latest technologies. ‘As you wll see, there are many inconsistencies between browsers that affect JavaScript develoners Query wll help you deal with cross-browser Inconsistencies (its one ofthe major easons why Query rapidly gained popularity amongst wed = == =) =. You need to learn to “think” like a computer because they solve tasks in different ways than you or I might approach them, Computers solve problems programmatically, they follow series of instructions, one after another. The typeof instructions they need are often cifferent to the typeof instructions you might give to another human. Therefore, thoughout th book you wil not ‘only learn the vocabulary and syntax that lavaScript uses, but you will also learn howto wt nstuctions that computers can follow. For example, when you lok tthe picture on the left how de you tll wich person s the tallest? ‘Acomputer would need expt, step-by-step Instructions, such as: 1. Find the height ofthe fst person [Link] or she the “tallest person” 3 Look atthe height ofthe remaiing people one- by-one and compare their height tothe tallest person" you have found so far 4,At each step, you find someone whose heights ‘reater than the curent “tallest person’ he or she ‘becomes the new tallest person [Link] you have checked alhe people tel me which one the tallest So the computer needst ook at each person in turn, and foreach ont performs atest Ave they taller than the curent alles! person?" Once it has done this foreach person it can give ts answer. rae asc ormocnasmns (8)DEFINING A GOAL & DESIGNING THE SCRIPT Consider how you might approach a different type of script. This example calculates the cost of a name plaque. Customers are charged by the letter. The ist thing you should do is deta your gals for the serot Ghat you wantit to schieve) Customers can have aname added toa plaque: each letter costs $5. When a ser enters aname, show them how much t wil eos Next, break tnt a saris of asks that have tobe performed n order to achieve te gals 1. The sritis triggered when the button sccked. 2tcallecs the name entered int the form fi 3: thehecks thatthe user has entered value 4. the user has not entered anything, message wil appear tling them to enter aname. 5a name hasbeen entered calculate the cost of ‘the sign by multiplying the numberof letters by the cost per letter 6. Show how much the plaque costs. (These numbers correspond with the flowchart on the iaht-hand page) CUSTOM SIGNAGE Enter name: CUSTOM SIGNAGE Enter name: rin ers nnsben ae a CUSTOM SIGNAGE Ls i HOMASSKETCHING OUT THE TASKS IN A FLOWCHART Often scripts will need to perform different tasks in different situations. You can use flowcharts to work out how the tasks fit together. The flowcharts show the paths between each step. i ‘Get he name eter int the fom t ' Ginn> @ Ccalelate the cost of he son ters rice) t ‘hoy the cout ofthe sl on te sereen ‘Arrows show how the script moves om one task tothe next. The cifferent shapes represent diferent ‘types of tasks. In some places there ave decisions which cause the code to follow eifterent paths. ‘You wil learn how to turn this exampleinto code in Chapter 2. You will also see many more examples of diferent lowchars throughout the book, and you wil meet code that helps you deal wit each of these types of situations, Some experienced programmers use move complex cancal reservations canceled |cancelBooking) | eating 4 rooms a2 werHoD what doce: cam » © | errr conser vane ot rooting roperty | gym tase ‘cancelBookingO) decreases value of bookings sroverty | boat we heckAvalabity()_sbtrct value of Bookings property ‘fom seus of rooms property ana Totus number of eam avBtaDie Ga) THE ABC OF PROGRAMMINGHOTEL OBJECT 1. When a reservations made, the book event res [Link] book event riggers the nakeBooking() method, which inreases the value ofthe bookings property 23. The vale ofthe bookings prop \yischangedto rellect how many rooms the hotel has avaiable, ‘OBJECT TYPE: CAR EVENT happens when: method call PROPERTIES brake driverslows down changespoed) | make eww GERI iver speeds up changespecso | QUIEN and closing tag for that web page, and the 1astHodi fied property ofthe dacurent object tells youthe date this page was last update,‘OBJECT TYPE: WINDOW location. http//mwwiavascripthock com/ PROPERTIES ur. hetes/wurjavascriptook com/ lastModitied 09/04/2014 15:58:57 tile Learn Javascript & jquery ‘Abook that toaches you inanicerway Se aa ne}THE DOCUMENT OBJECT REPRESENTS AN HTML PAGE Using the document object, you can access and change what content users see on the page and respond to how they interact with it Like other objects that represent real-world things, the docunent object has: PROPERTIES Properties describe characteristics of the curent web page (such as the tte ofthe page). METHODS: Methods perform asks associated with the ‘document currently leaded in the browser (such ‘8 geting information rom a specified element or ‘adding pew content) EVENTS You can respond to events, suchas a user clicking tapping onan element @ wenscor ocearne Because all major web browsersimplement the docunent abjectin the same way, the people who ‘reat the browsers hove alrend: ‘© implemented properties that you can access to find out about the curent page in the browser '© Written methods that achieve some common tasks that you are likely to want todo with an HTML page So you wil elearning how to work with this object. Infact the docunent objects just on of set of objects that all mor browsers support. When the browse ereatesamedel ofa web page, tnt oly creates a document object, butt also creates 2 new object foreach element on the page Together these objects ar described inthe Document Object ‘Model, which yu will meetin Chapter 5HOW A BROWSER SEES A WEB PAGE In order to understand how you can change the content of an HTML Pee Seg ee OL ean Pe ee seas Toa Ce eo Tad create Usa ET ar ad Perna) ead a ee Pe acre mS ag instructions (in JavaScript) into instructions the computer can follow. eee Tee aThe bro St) Lo]SUMMARY THE ABC OF PROGRAMMING B: How do computers fit in with the world around them?HOW DO! WRITE A SCRIPT FORA WEB PAGE?HOW HTML, CSS, & JAVASCRIPT FIT TOGETHER Before diving into the JavaScript language, you need to know how it will fit together with the HTML and CSS in your web pages. Web developers usually tak about tvee languages that ar ured to create web pages: HTML, CSS, and JavaScript CONTENT LAYER hte files ‘This is where the content of the page ives. The HTML gives the page structure and adds, semantics, Where posible, am to keep the ‘te languages in separates, with the HTML page linking to CSS and JavaScript fies {css} PRESENTATION LAYER ses fies ‘The CSSenhances the HTML age with ules that statehow the HTML conten is presented ackarounds, borders, box dimensions, colors fonts, te.) Programmer olten lero this 88 separation of concerns Each lanauage forms a separate layer wth citferent purpose, Each ayer, from ett right, bulds on the previous one. javascript () BEHAVIOR LAYER ‘Thisis where we can change how the page behaves, adding interactivity. We wil im to keep ‘as much of our JavaScript as possible in separate es.‘Asmore and more web-enabled element to tell the browser it is coming across a script. Its sr attribute tells people where the JavaScript file is stored. -<100cT¥PEhem> “ht head “ © In your code editor enter the HTML shown onthe left. Save this ile withthe name add-content. hem) elements Constructive tanp: Co. used toad the JavaScript fle script sre="s/[Link]*> ‘nto the page Ithas an atribute tht the script you crated. ne pat ty This tls the browser to find and load the seit le Gust ke the srcattribute onan 9g) @ Open the HTL file in your browser You should see thatthe JavaScript has added a gresting inthis ease, Good Afternoon! to the page. (These greetings are coming from the JavaScript fie they ae notin the HTML file) Pleate note internet Exlorer sometimes prevens avaScrist running when you open page stored on your hard dive. tis alfects you, please try Chrome, Felox, Opera or SafrinsteadTHE SOURCE CODE IS NOT AMENDED If you look at the source code for the example you just created, you will see that the HTML is still exactly the same the browser) © The source ofthe web page does not actualy show the new clement that ha been added into the page; it just shows the nto the avaSerot le the book Ge) THe ABc oF PROGRAMMINGPLACING THE SCRIPT IN THE PAGE You may see JavaScript in the HTML between opening tags (but it is better to put scripts in their own files). stocriee wst= Frat. ey opning te aoe" ratiremvng te se aicscanstrative sep co. - itt mbterteteet” heefe‘essfotast ponontashornen bas = ep uoonebe sero! tag and the closing ‘Scriancnet wt secon >) ta The eration Sete leer nededbecasethe Bron a orders and toutes plese eat Inaction the TL poe cosabaeenye siete \s noted on p44, itis better it saad ono not to ma JavaScript in your HTML pageslite this, but ts ‘mentioned ee a you may comeacros ths technique © open the TM fein your web rower and tin were @ ‘etn wten othe pe Conroe & Co. AAs you may have guess, [Link]) writes iaccoaa ‘content into the document (he web page. tis simple way “acta toadd content to a page, but not always the best Chapter S discusses various ways to Update the content ofa page.HOW TO USE OBJECTS & METHODS Be Ree Se cn a eee ed Programmers refer to this as calling a method of an object. Ce eee Sea one cree resent: eee eres peers ———— — [Link]('Good afternoon!' (javier Siena ee ot ret eer pee Pere Cee ee eee ete See fener callthe object and method, andthe dacunent object, and lots the words appear on the screen, et ee er) fee eeeernr ire meee i Sete aa et en arte ee Peart epee (OmenJAVASCRIPT RUNS WHERE IT IS FOUND IN THE HTML MTree eee ea et ace eC) cu eee ea ee cs Pas GOOD AFTERNOON! SeaSUMMARY THE ABC OF PROGRAMMING C: How do | write a script for a web page? >JAVASCRIPT INSTRUCTIONSIn this chapter, you will start learning to read and write JavaScript. You will also learn how to give a web browser instructions you want it to follow. ‘THE LANGUAGE: GIVING INSTRUCTIONS: SYNTAX AND GRAMMAR, FOR A BROWSER TO FOLLOW Like any new language, there are new Web browsers (and camputersin genera words to learn (the vocabulary) and ules approach tasks ina very diferent way than forhow these canbe put together (he ‘ahuman might Your instructions need to srommar and syntax of the language). refiect how computers get things done. ‘We wilstar with few of the key building blocks ofthe langage dnd look at how they con be used to wrte some very basic scrips consisting ofa fw simple steps) before going onto look at some more complex concep in subsequent chapters. (Gy msec anvearnrvereer keSTATEMENTS A script is a series of instructions that a computer can follow one-by-one. Each individual instruction or step is known as a statement Statements should end with a semicolon, ‘We wllook at what the cade onthe right does shot but forthe momeat note tat ‘© Eachol the lines ofcodein green sa statement (©The pink curly braces indicate the start and end cof cade black (Each code block could contin ‘many more statements) 1© The code in purple determines which code should run (es you ill se on p145). JAVASCRIPT IS CASE SENSITIVE JavaScripts case sensitive so hourNow means ‘something diferent to Hour or HOURKOW. ‘STATEMENTS ARE INSTRUCTIONS AND EACH ONE STARTS ON A NEW LINE Atatementis an indviual instruction that the ‘computer shoud follow. Each one shoud start on 9 ‘ew line and end witha semicolon. This makes your ‘code casero read and oo The semicolon aso tls the JavaScript interpreter when astep is over indicating that it should move tothe nest step. var today = new Date(); var hourNow = [Link](); var greeting if (bourtow > 18) ( greeting = ‘Good evening's } else if (hourtow > 12) ( greeting = ‘Good afternoon’ | else if (hourtiow > 0) ( greeting = "Good morning’; } else ( greeting = 'Welcone'; docunent..write(greet ing) STATEMENTS CAN BE ORGANIZED INTO CODE BLOCKS Some statements ae surrounded by curly braces ‘these are known a code blocs, The closing curly braces not followed bya semicolon ‘Above, each code block contains one statement related to what the current time i. Code blocks willoften beused to group tegether many more statements, Ths helps programmers organize their ‘code and makesit more readable.COMMENTS You should write comments to explain what your code does. They help make your code easier to read and understand. This can help you and others who read your code. (* This script displays a greeting to the user based upon the current tine. It 4s an example from JavaScript & jQuery book */ var today = new Date(s var hourtow » today getHours greetings /f Create 2 +1] Find the // Display the appropriate greeting based on 44 (hourkow > 18) { greeting ~ "Good evening's ) else if (nourtow > 12) { greeting = "Good afternoon's } else if (nourtow > 0) { 1 Seton = Cotsen greeting = ‘Welcome; 1 document write(areet ing); MULTI-LINE COMMENTS To write 2 comment that stretches ver more than one line, you use multitine comment, starting with the /* characters and ending withthe */ characters. ‘Anything between these characters isnot processed by the JavaScript interpreter. ‘Mult-ine comments ar aften used for descriptions ‘of how the seript works, orto prevent a section of the script from runing when testing it new date object current hour the current tine JavaScript code is green Multiline comments re pink Single-fine comments are gray ‘SINGLE-LINE COMMENTS Ira singletine comment, anything that follows the two forward slash characters //on that line wil not bbe processed by the JavaScript interpreter. Single- line comments are often used for short descriptions ‘of what the code doing {Good use of comments willhelp you you come back o your code aller severa days or months. ‘They aso lp those who are new to your code.WHAT IS A VARIABLE? Ascript store the bits of information it needs to do its job. It can store this data in variables. ill have to temporarily ‘When you write JavaScript, youhave to tele Interpreter every individual step that you want it to perform. This sometimes involves more deal than you might expect Think bout calculating the area of wall ia math the area of arectange is obtained by muipying two with x height = oreo You may beable to de calculations Wie thisin your head, but when writing 9 erp to de this ‘aleulation, you need to give the computer very detailed instructions. You might elt to perform the {allowing four steps inorder: 1. Remember the vale for width [Link] the value for height ‘3. Multiply width by height to get the oreo [Link] the result othe user Inthis case, you would use variables to“ernember the values for width and eight. This ls ilustrates how a script contains very explicit instructons about ‘exactly what you want the computer todo.) You can compare variables to short-term memory, because once you leave the page the browser will forget any information holds,A variable is a good name for this, concept because the data stored ina variable can change (or vary) each time a script runs. No matter what the dimensions of any inaviduat wallare you know that you find its ara by tiplyingthe width ofthat wal by its height Similarly, serps often need to achieve thesame soa even when they are run wih liferent data, so ‘arabes canbe used to represent values in your scp that are likely ochonge. The results ai to be calelated 0” computed using the data stored in the variables, The use of variables to represent numbers or other nds of datas very ilar tothe concept of algebra (here eters are used to represent numbers. There one key ditterence, however. The equals sign does something very diferent in programming (as you wil [Link] the next two pages. BASIC JAVASCRIPT INS ns (59)VARIABLES: HOW TO DECLARE THEM Before you can use a variable, you need to announce that you want Ce a eee eee ee eee ens DRE Soca quantity; itn 6 on ee ee aa edVARIABLES: HOW TO ASSIGN THEM A VALUE CNM te ERC aCe Oa aun] PO Oa Rae Ce UE ue Rea the variable. (ofr Ua aA = er See) ere ssignment opera rrr valueto peer ee een reeDATA TYPES JavaScript distinguishes between numbers, strings, and true or false values known as Booleans. NUMERIC DATA TYPE “The numeric datatype handles numbers. 0.75 For tasks that involv counting ‘or calculating sums, you wil use numbers 0-9, Fr example, Five thousand, two hundeed ond Seventy-two would be written 5272 (note there smo comma betwoen the thousands and the hundreds. You can also have negative numbers (such .35-23678) and decimals (hee quarters is witen 8 0.75) Numbers are not ony used for ‘things like caleuatrs;they ‘are ago used for tasks such 25 determining the sie ofthe screen, moring the position of anelement ona page, or setting the amount of time an element should take to fade, STRING DATA TYPE ‘Thestrings data type consists of letters and ether charactor, "Hi, Ivy!" Note how the string datatypes ‘enclosed withina pair af quotes. These canbe single or double quotes, but the opening quote ‘must match the closing quot, ‘Strings can be used when working with any kind of tot ‘They are fequertly used toadd ‘new content into a page and they {an contain HTML markup. BOOLEAN DATA TYPE Boolean datatypes can have one oftwo values: true or false. true Itmight seem alittle abstract at first, but the Boolean datatypes actully very helpful. You canthinkof tattle tke 2 light switch itis ether on or of ‘Asyou wll seein Chapter 4, Booleans ae helpful when etermining which part ofa script shoul un Inaddtion to these tree data types, JavaScript aso as others (arrays, ‘objects, undefined nd nul) that you wll met in later chapters. Unlike some other programming languages, when declaring avaiable in JavaScript, you donot need to specify what typeof dat ll hold JASIC JAVASCRIPT INSTRUCTIONS.USING A VARIABLE TO STORE A NUMBER nm cat/is/[Link] Heft thre variables are created teaver sar an var pees peal Sheet: Invi He : © quantity holds the number hie Sissons auantity = 4s ta tle ctl ‘total = price * quantity; the tiles var el = [Link]élenentById("cost") "Note that the numbers ae not Meeatontent = totals trunnion nets reste as eed ‘Srvutleyoucan unto = theron e st EST aa at Value (much ike you might have done in aigebra). Here, the total costs calculated by mutilying the pice ofa single tile by the numberof es the customer wants, “Elderflowers/ni> ‘Custom Signages/h2>' + saying. length +
" [insg += ‘' + [Link]() +
|nsg += " ' + [Link]() + ' ' + [Link](12) + " ' + saying. indexO#(ee!) + " " + saying. lastIndexOf("e") + *=/p>'s
fee's
Insg #= ‘ " + [Link](8, 14) + ‘ ' + [Link]('me', ‘w') + ‘ Copyright Bcopys' + year + ‘









You might also like