jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of...

59

Transcript of jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of...

Page 2: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

jQuery andJavaScript

P H R A S E B O O K

Page 3: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

This page intentionally left blank

Page 4: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Brad Dayley

jQuery andJavaScript

P H R A S E B O O K

Upper Saddle River, NJ • Boston • Indianapolis • San FranciscoNew York • Toronto • Montreal • London • Munich • Paris • Madrid

Cape Town • Sydney • Tokyo • Singapore • Mexico City

Page 5: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Many of the designations used by manufacturers and sellers to distinguish theirproducts are claimed as trademarks. Where those designations appear in this book,and the publisher was aware of a trademark claim, the designations have been print-ed with initial capital letters or in all capitals.

The author and publisher have taken care in the preparation of this book, but makeno expressed or implied warranty of any kind and assume no responsibility for errorsor omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs containedherein.

For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus,or branding interests), please contact our corporate sales department at [email protected] or (800) 382-3419.

For government sales inquiries, please contact [email protected].

For questions about sales outside the U.S., please [email protected].

Visit us on the Web: informit.com/aw

Library of Congress Control Number: 2013950281

Copyright © 2014 Pearson Education, Inc.

All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior toany prohibited reproduction, storage in a retrieval system, or transmission in anyform or by any means, electronic, mechanical, photocopying, recording, or likewise.To obtain permission to use material from this work, please submit a written requestto Pearson Education, Inc., Permissions Department, One Lake Street, Upper SaddleRiver, New Jersey 07458, or you may fax your request to (201) 236-3290.

ISBN-13: 978-0-321-91896-3ISBN-10: 0-321-91896-7

First printing: December 2013

Acquisitions EditorMark TaberManaging EditorKristy HartProject EditorKatie Matejka

Copy EditorKaren GillIndexerPublishingServices,WordWise,Larry Sweazy

ProofreaderKathy RuizTechnical ReviewerPhil BallardEditorial AssistantVanessa Evans

Cover DesignerChuti PrasertsithSenior CompositorGloria Schurick

Page 6: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Dedication

For D!A & F

Page 7: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Contents

1 Jumping into jQuery, JavaScript, and the World of Dynamic Web Development 1

Understanding JavaScript 2

Introducing jQuery 4

Introducing jQuery UI 7

Introducing jQuery Mobile 9

Configuring Browser Development Tools 12

2 Using the JavaScript Language 15

JavaScript Syntax 15

Defining and Accessing Data 16

Defining Functions 20

Manipulating Strings 21

Manipulating Arrays 25

Applying Logic 29

Math Operations 31

Working with Dates 36

3 Interacting with the Browser 43

Writing to the JavaScript Console 43

Reloading the Web Page 44

Redirecting the Web Page 44

Getting the Screen Size 45

Getting Current Location Details 45

Accessing the Browser 47

Using the Browser History to Go Forward andBackward Pages 49

Creating Popup Windows 50

Manipulating Cookies 52

Adding Timers 55

Page 8: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

viiContents

4 Accessing HTML Elements 59

Finding HTML Elements in JavaScript 59

Using the jQuery Selector to Find HTML Elements 61

Chaining jQuery Object Operations 75

Navigating jQuery Objects to Select Elements 76

5 Manipulating the jQuery Object Set 83

Getting DOM Objects from a jQuery Object Set 84

Converting DOM Objects into jQuery Objects 84

Iterating Through the jQuery Object Set Using .each() 85

Using .map() 87

Assigning Data Values to Objects 89

Adding DOM Elements to the jQuery Object Set 91

Removing Objects from the jQuery Object Set 91

Filtering the jQuery Object Results 92

6 Capturing and Using Browser and User Events 95

Understanding Events 96

Adding Event Handlers 99

Controlling Events 107

Using Event Objects 111

Handling Mouse Events 115

Handling Keyboard Events 118

Form Events 122

7 Manipulating Web Page Elements Dynamically 125

Getting and Setting DOM Element Attributes and Properties 126

Page 9: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Getting and Setting CSS Properties 130

Getting and Manipulating Element Content 139

8 Manipulating Web Page Layout Dynamically 143

Hiding and Showing Elements 143

Adjusting Opacity 146

Resizing Elements 149

Repositioning Elements 152

Stacking Elements 156

9 Dynamically Working with Form Elements 159

Getting and Setting Text Input Values 160

Checking and Changing Check Box State 161

Getting and Setting the Selected Option in a Radio Group 162

Getting and Setting Select Values 164

Getting and Setting Hidden Form Attributes 166

Disabling Form Elements 167

Showing/Hiding Form Elements 170

Forcing Focus to and Away from Form Elements 172

Controlling Form Submission 175

10 Building Web Page Content Dynamically 177

Creating HTML Elements Using jQuery 178

Adding Elements to the Other Elements 179

Removing Elements from the Page 184

Dynamically Creating a Select Form Element 186

Appending Rows to a Table 189

Inserting Items into a List 191

Creating a Dynamic Image Gallery 193

Adding HTML5 Canvas Graphics 196

viii Contents

Page 10: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

11 Adding jQuery UI Elements 201

Adding the jQuery UI Library 201

Implementing an Autocomplete Input 203

Implementing Drag and Drop 205

Adding Datepicker Element 212

Using Sliders to Manipulate Elements 215

Creating a Menu 219

Adding Tooltips 223

12 Animation and Other Special Effects 227

Understanding jQuery Animation 228

Animating Visibility 234

Making an Element Slide Back to Disappear 238

Animating Show and Hide 242

Animating Resizing an Image 246

Animating Moving an Element 248

13 Using AJAX to Communicate with Web Servers and Web Services 251

Understanding AJAX 251

AJAX from JavaScript 261

AJAX from jQuery 267

Handling jQuery AJAX Responses 282

Using Advanced jQuery AJAX 285

14 Implementing Mobile Web Sites with jQuery 291

Getting Started with jQuery Mobile 291

Building Mobile Pages 302

Implementing Mobile Sites with Multiple Pages 306

Creating a Navbar 314

Applying a Grid Layout 316

Implementing Listviews 320

ixContents

Page 11: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

x Contents

Using Collapsible Blocks and Sets 326

Adding Auxiliary Content to Panels 327

Working with Popups 329

Building Mobile-Friendly Tables 332

Creating Mobile Forms 334

Index 341

Page 12: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

AcknowledgmentsI’d like to take this page to thank all those who madethis title possible. First, I thank my wonderful wife andboys for giving me the inspiration and support I need.I’d never make it far without you.Thanks to MarkTaber for getting this title rolling in the right direc-tion; Karen Gill for turning the ramblings of my techiemind into coherent text; Phil Ballard for ensuring theaccuracy in the book and keeping me honest; KathyRuiz and Gloria Schurick for making sure the book isthe highest quality; Larry Sweazy for making sure thatthe readers can actually find what they look for in thebook;Tammy Graham and Laura Robbins for theirgraphical genius; Chuti Prasertsith for the stylish andsleek cover; and Katherine Matejka for all her hardwork in making sure this book is the best it can be.You guys are awesome!

Page 13: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

About the AuthorBrad Dayley is a senior software engineer with 20years of experience developing enterprise applications.He has used HTML/CSS, JavaScript, and jQueryextensively to develop a wide array of web pages rang-ing from enterprise application interfaces to sophisti-cated rich Internet applications to smart interfaces formobile web services. He is the author of PythonDeveloper’s Phrasebook and Sams Teach Yourself jQuery andJavaScript in 24 Hours.

Page 14: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

We Want to Hear from You!As the reader of this book, you are our most importantcritic and commentator.We value your opinion andwant to know what we’re doing right, what we coulddo better, what areas you’d like to see us publish in,and any other words of wisdom you’re willing to passour way.

You can email or write directly to let us know whatyou did or didn’t like about this book—as well as whatwe can do to make our books stronger.

Please note that we cannot help you with technical problemsrelated to the topic of this book, and that due to the high vol-ume of mail we receive, we might not be able to reply to everymessage.

When you write, please be sure to include this book’stitle and author as well as your name and contactinformation.

Email: [email protected]

Mail: Reader FeedbackAddison-Wesley Developer’s Library800 East 96th StreetIndianapolis, IN 46240 USA

Reader ServicesVisit our Web site and register this book atinformit.com/register for convenient access to anyupdates, downloads, or errata that might be availablefor this book.

Page 15: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

This page intentionally left blank

Page 16: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

This page intentionally left blank

Page 17: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

3Interacting withthe Browser

Dynamic web pages often require you to access andin some cases even manipulate things beyond theHTML elements. JavaScript provides a rich set ofobjects and functions that allow you to access informa-tion about the screen, browser window, history, andmore.

The phrases in this chapter describe ways to use thescreen, window, location, and history objects that pro-vide JavaScript with an interface to access informationbeyond the web page.Additional phrases describe uti-lizing those objects to implement cookies, popup win-dows, and timers.

Writing to the JavaScriptConsoleconsole.log("This is Debug"); //"This is Debug" is

➥displayed in console

var x=5;

console.log("x="+x): //"x=5" is displayed in console

Page 18: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

The JavaScript console can be an important tool whendebugging problems in your jQuery and JavaScriptcode.The console log is simply a location where youcan view data output from the JavaScript code. Each ofthe major browsers has a console log tool that displaysthe output.

To output data to the console log, useconsole.write(DEBUG_STRING) and pass it the text thatyou want to display on the console.

Reloading the Web Page

44 CHAPTER 3 Interacting with the Browser

location.reload()

A useful feature of JavaScript is the ability to force thebrowser to reload the current web page.You may wantto reload the web page because data has changed onthe server or a certain amount of time has elapsed.Thelocation.reload() method requests that the browserreload the current URL.

Redirecting the Web Pagelocation.href="newpage.html";

location.href="http://jqueryin24/index.html;

Another extremely useful feature of JavaScript is theability to redirect the browser away from the currentURL to another location.You do this by setting thelocation.href value to a new URL.The new URLcan be a full address, such ashttp://mysite.com/newlocation/index.html, or a rela-tive location to the current URL, such as page2.html.

Page 19: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Getting the Screen Size

45Getting Current Location Details

screen.availHeight; // returns screen height in

➥pixels

screen.availWidth; // returns screen width in pixels

An important feature of JavaScript these days is theability to get the screen size.The screen sizes ofbrowsers vary so much that you often need to use dif-ferent sets of code for larger, medium, or smallerscreens.To get the screen size, use thescreen.availHeight and screen.availWidth attributes.These values are specified in the number of pixels.

Getting Current LocationDetailsThe JavaScript location object provides an easy way toget various pieces of information about the URL theuser is currently viewing. Because JavaScript andjQuery code are often used across multiple pages, thelocation object is the means to get information aboutwhat URL the browser is currently viewing.The fol-lowing sections provide some phrases that provideinformation about the browser’s current location.

Finding the Current Hashlocation.hash

The location.hash value returns the current hash, ifany, that the browser is using.This is useful when youare displaying a web page with multiple hash anchors.The hash provides a context to the location on thepage the user actually clicked.

Page 20: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Getting the Host Name

46 CHAPTER 3 Interacting with the Browser

location.hostname

The location.hostname value returns the domain nameof the server that sent the page to the user.This is justthe portion after the protocol but before the portnumber or path.This allows you to determine whichserver to send AJAX requests back to. Often, multipleservers may handle the web site, but you may want tointeract only with the server that served the web pagein the first place.

Looking at the File Pathlocation.pathname

The location.pathname returns the path that the pagewas loaded from on the server.The pathname also pro-vides a context as to what page the user is looking at.

Getting the Query Stringlocation.search

The location.search value returns the query stringthat was passed to the server to load the page.Typically,you think about a query string as a server-side scripttool. However, it can be just as valuable to JavaScriptcode that manipulates the data returned from the server and requests additional information from theserver via AJAX.

Page 21: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Determining If the Page Is Viewedon a Secure Protocol

47Accessing the Browser

location.protocol

The easiest way to determine if a page is being viewedfrom a secured location on the server is to look at thelocation.protocol value.This value will be http onregular requests or https on secure requests.

Accessing the BrowserAnother important object built into JavaScript is thewindow object.The window object represents thebrowser and provides you with a wealth of informa-tion about the browser position, size, and much more.It also allows you to open new child windows, closewindows, and even resize the window.

Getting the Max Viewable WebPage Sizewindow.innerHeight; // returns browser view port

➥height in pixels

window.innerWidth; // returns browser view port

➥width in pixels

The window object provides the innerHeight andinnerWidth of the browser window.These values repre-sent the actual pixels in the browser window that theweb page will be displayed within.This is a criticalpiece of information if you need to adjust the size andlocation of elements on the web page based on theactual area that is being displayed.

Page 22: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Setting the Text Displayed in theBrowser Status Bar

48 CHAPTER 3 Interacting with the Browser

window.status = "Requesting Data From Server . . .";

The browser has a status bar at the bottom.You can setthe text that is displayed there to provide to the useradditional information that does not belong on thepage, such as the server name, current status ofrequests, and more.To set the text displayed in thebrowser status bar, set the window.status value equal tothe string you want displayed.

Getting the Current Location in theWeb Pagewindow.pageXOffset;

// number of pixels the page has scrolled to the

➥right

window.pageYOffset;

// returns number of pixels the page has scrolled

➥down

When writing dynamic code, it is often necessary todetermine the exact location in the web page that iscurrently being viewed.When the user scrolls down orto the right, the position of the page to the frame ofthe browser view port changes.

To determine the number of pixels the page hasscrolled to the right, use the window.pageXOffset attrib-ute.To determine the number of pixels the page hasscrolled down, use the window.pageYOffset attribute.

Page 23: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Opening and Closing Windows

49Using the Browser History to Go Forward and Backward Pages

//Opens a new blank window, writes to it, and then

➥closes it.

var newWindow = window.open();

newWindow.document.write("Hello From a New Window");

newWindow.close();

//Opens another URL in a new window

window.open("http://google.com");

The window object also provides a set of methods thatallow you to create and manage additional child win-dows from your JavaScript code.

For example, the window.open(URL) method opens anew window and returns a new window object. If youdo not specify a URL, the browser opens a blank pagethat can be written to using the window.documentobject.

You can call .close() on window objects that youhave created, and they will be closed.

Using the Browser History toGo Forward and BackwardPageshistory.forward(); //forward 1 page

history.back(); //backward 1 page

history.go(-2); //backward 2 pages

The browser keeps track of the pages that have beennavigated to in a history. JavaScript allows you toaccess this history to go forward or backward pages.This allows you to provide forward and backward con-trols to your web pages.You can also use this feature toprovide bread crumbs displaying links to multiplepages back in the history.

Page 24: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

To go forward one page, use history.forward().To gobackward one page, use history.back().

To go forward or backward multiple pages, use history.go(n), where n is the number of pages.A neg-ative number goes backward that many pages, and apositive number goes forward that many pages.

Creating Popup Windows

50 CHAPTER 3 Interacting with the Browser

var result = confirm("You Entered " + response +

"is that OK?");

if(result){ alert("You Said Yes.") }

else {alert("You Said no.")}

Window objects provides several different methodsthat allow you to launch popup windows that you caninteract with for alerts, prompts, and notifications.Thepopup windows are displayed, and the user needs tointeract with the popup before continuing to accessthe web page.

There are three kinds of popup boxes that can be created:

n alert(msg)—Launches a popup window that dis-plays an alert message and provides a button toclose the popup.

n confirm(msg)—Launches a popup window thatdisplays a confirmation and message provides anOK and a Cancel button, which both close thepopup. If you click the OK button, the returnvalue from confirm() is true; otherwise, it is false.

Page 25: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

n prompt(msg)—Launches a popup window that dis-plays the message, a text box for input, and an OKand Cancel button, which both close the popup.If you click the OK button, the return value fromprompt() is the text typed into the text box; other-wise, it is false.

The code that follows illustrates these popup boxes, asshown in Figure 3.1.

01 <html>

02 <head>

03 <title>Python Phrasebook</title>

04 <meta charset="utf-8" />

05 <script type="text/javascript"

06 src="../js/jquery-2.0.3.min.js"></script>

07 <script>

08 var response = prompt("What is the airspeed "

➥+

09 "velocity of an unladen swallow:");

10 var result = confirm("You Entered " +

➥response +

11 "is that OK?");

12 if(result){ alert("You may pass.") }

13 else {alert("None Shall Pass.")}

14 </script>

15 </head>

16 <body>

17 </body>

18 </html>

ch0301.html

51Creating Popup Windows

Page 26: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Figure 3.1 Various popup boxes, with the resultsbeing passed from popup to popup using

JavaScript.

By the way

It is often much better to create a fixed position <div>element with an overlay than to use these popupboxes because you have much more control over them.I’ll show you how to do just that a little later in thebook.

Manipulating CookiesA common task in JavaScript is getting and settingcookies in the browser. Cookies allow you to storesimple key value pairs of information in the browser ina persistent manner.You can access the cookies by the

52 CHAPTER 3 Interacting with the Browser

Page 27: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

server-side scripts and JavaScript to determine whatthose values are.

You can access cookie information using the document.cookie object.This object contains all thecookies in the string format name=value; name=value;….

Setting a Cookie Value in theBrowser

53Manipulating Cookies

function setCookie(name, value, days) {

var date = new Date();

date.setTime(date.getTime()+(days*24*60*60*1000));

var expires = "; expires="+date.toGMTString();

document.cookie = name + "=" + value +

expires + "; path=/";

}

To add a new cookie for your web site, setdocument.cookie = "name=value; expireDate; path;";.

The expire date needs to be a date set using.toGMTString(), and the path is the path on your website that the cookie applies to.

Getting a Cookie Value from theBrowserfunction getCookie(name) {

var cArr = document.cookie.split(‘;’);

for(var i=0;i < cArr.length;i++) {

var cookie = cArr[i].split("=",2);

cookie[0] = cookie[0].replace(/^\s+/,"");

if (cookie[0] == name){ return cookie; }

}

}

To get the value of the cookie, split the document.cookie value using the ; character, and then iterate

Page 28: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

through the resulting array until you find the nameyou are looking for.

Example Getting and SettingCookiesThe following code shows a full example of settingand getting cookies.When the code is run, two cook-ies are set: one for name and the other for language.The cookies are then retrieved from the browser andwritten to the web page, as shown in Figure 3.2.

01 <html>

02 <head>

03 <title>Python Phrasebook</title>

04 <meta charset="utf-8" />

05 <script type="text/javascript"

06 src="../js/jquery-2.0.3.min.js"></script>

07 <script>

08 function setCookie(name, value, days) {

09 var date = new Date();

10 date.setTime(date.getTime()+(days*24*60*60*

➥1000));

11 var expires = "; expires="+date.toGMTString

➥();

12 document.cookie = name + "=" + value +

13 expires + "; path=/";

14 }

15 function getCookie(name) {

16 var cArr = document.cookie.split(‘;’);

17 for(var i=0;i < cArr.length;i++) {

18 var cookie = cArr[i].split("=",2);

19 cookie[0] = cookie[0].replace(/^\s+/,"");

20 if (cookie[0] == name){ return cookie; }

21 }

22 }

54 CHAPTER 3 Interacting with the Browser

Page 29: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

23 setCookie("name", "Brad", 1);

24 setCookie("language", "English", 1);

25 document.write("<h3>Cookies</h3>");

26 var c1 = getCookie("name");

27 document.write(c1[0] + " is set to "+ c1[1]

➥+"<br>");

28 var c2 = getCookie("language");

29 document.write(c2[0] + " is set to " +

➥c2[1]);

30 </script>

31 </head>

32 <body>

33 </body>

34 </html>

ch0302.html

55Adding Timers

Figure 3.2 Adding cookie output using JavaScript.

Adding TimersAnother useful feature of JavaScript is the ability to settimers that execute a function or evaluate an expres-sion after a certain amount of time or on a specificinterval.

Using timers allows you to delay the execution ofcode so that it does not need to happen at the exactmoment an event is triggered or the page is loaded.The following phrases show you how to create timersto delay code execution and to apply recurringactions.

Page 30: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

Adding a Delay Timer

56 CHAPTER 3 Interacting with the Browser

function myTimer () {

alert("Timer Function Executed");

}

var timerId = setTimeout(myTimer, 10000);

To simply delay the execution of code for a certainamount of time, use the setTimeout(code, ms) method,where code is either a statement or a function that exe-cutes when the time expires. ms is the number of mil-liseconds. For example, to execute a function namedmyTimer() in 10 seconds, you would use the following:

setTimeout(myTimer, 10000);

Cancel a Timerfunction myTimer () {

alert("Timer Function Executed");

}

var timerId = setTimeout(myTimer, 10000);

clearTimeout(timerId); //timer will not execute

At any point before the time runs out and the code isexecuted, you can clear the timer by calling theclearTimeout(id) method using the ID returned fromsetTimeout(). Once the timer has been cleared, it doesnot execute.You need to keep track of the ID returnedfrom setTimeout() using a variable.

Adding a Recurring Timervar statusTimerId;

var status = "OK";

//checks status every minute as long as it is "OK"

function checkStatus () {

if(status == "OK"){

Page 31: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

You can also start a timer that triggers on a regularinterval using the setInterval(function, ms) method.This method also accepts a function name and mil-liseconds as arguments. Inside the function, you needto call set interval again on the same function so thatthe code will be called again.

To turn off the recurring timer, simply do not callsetInterval() again inside the timer function, or useclearInterval() outside the function.

57Adding Timers

alert("Status OK");

statusTimerId = setInterval(checkStatus, 60000);

} else {

alert("Status Failed");

}

}

statusTimerId = setInterval(checkStatus, 60000);

Page 32: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

This page intentionally left blank

Page 33: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

A

absolute values,calculating, 34

accessingbrowsers, 47-49

accessing cookies,52-55

history, 49HTML

chaining object operations, 75-76

elements, 59navigating objects,

76-82searching elements,

59-68, 71-74jQuery in JavaScript, 6libraries, 7Mobile, 10variables, 16

addEventListener() function, 103

addingauxiliary content to

panels, 328borders, 134conditional blocks of

code, 30cookies, 53

dividers to lists, 324DOM elements to

objects, 91elements to elements,

179-183event handlers, 99, 105forms

elements, 336mobile, 334-336, 340

initialization code, 100items to lists, 191-193JavaScript

to HTML docu-ments, 3

loading from external files, 4

jQuery to web pages,5-6

labels, 335mouse-click-handling

code, 115navigation buttons,

307, 311, 314page load event

handlers, 99rows to tables, 189-191tables, 333timers, 55-57transitions, 308

Index

Page 34: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

UI elementsapplying sliders,

215-216, 219attaching datepicker,

212-215coding tooltips,

223-225creating menus,

220-222downloading

libraries, 201-202dragging/dropping,

205-212implementing auto-

complete, 203-205jQuery, 201

adjusting opacity, 146-149.See also modifying

adjValues() function, 197AJAX

asynchronous commu-nication, 253-254

cross-domain requests, 254

GET/POST requests, 255JavaScript, 261-267jQuery, 267-289overview of, 251-252response data types,

256-259ancestors, searching, 80.animate() method,

228-229animation, 227-228

.hide() method, 242

.show() method, 243

.toggle() method,243-245

CSS settings, 228-229delaying, 233images

moving elements,248-250

resizing, 246-248queues, 231sliding toggles, 239-242stopping, 232-233visibility, 234-238

appendingbottom of element’s

content, 180elements, 141rows to tables, 189-191text, 140

applications, Mobile, 9-12applying

AJAX, 251-252asynchronous

communication,253-254

cross-domainrequests, 254

GET/POST requests,255

JavaScript, 261-267jQuery, 267-289response data

types, 256-259event objects, 111-114filters to selectors, 74for() loops, 31grid layouts,

316-317, 320

adding342

Page 35: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

logic, 29-31.map() method, 87-88nested lists, 322popups, 329, 332power functions, 35right-click, 117-118selectors, 62sliders, 215-216, 219trigonometric

functions, 35while() loops, 30

arguments, 20arrays

combining, 26creating, 18items

deleting, 27detecting, 27

iterating, 31manipulating, 25-27sorting, 28splicing, 26

assigningdata values to

objects, 89event handlers in

HTML, 101asynchronous

communication, 253-254attaching datepicker

element, 212-215.attr() method, 126, 166attributes, selecting

based on HTML, 64autocomplete,

implementing, 203-205

B

back buttons, creating, 309behavior, events, 107-110blocks, adding code, 30.blur() method, 173borders, adding, 134bottom of element’s

content, appending, 180browsers. See also

interfacesaccessing, 47-49cookies, modifying,

52-55current location details,

45-47development tools,

configuring, 12-13events

adding event handlers, 99-106

forms, 122-123keyboards, 118-120managing, 107-110mouse, 115-118objects, 111-114overview of, 96types, 96, 99

history, accessing, 49JavaScript consoles,

applying, 44navigating, 43popup windows,

creating, 50-51screens, sizing, 45timers, adding, 55, 57

browsers 343

Page 36: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

web pagesredirecting, 44reloading, 44

building mobile pages, 302-304

buttonImage option, 213buttonImageOnly option, 213buttons

back, creating, 309navigation

adding, 307,311, 314

positioning, 308split lists, 324

C

calculating absolute values, 34

calling functions, 20cancelling timers, 56Cascading Style Sheets.

See CSSscase, modifying strings, 24CDNs (Content Discovery

Networks), 5, 9chaining object operations,

75-76change option, 216.changePage() method, 298changes to text,

detecting, 119characters

searching, 22special, string

objects, 21

check box state, modifying,161-162

checkingitems in arrays, 27for substrings, 25

children, retrieving elements, 77

Chrome, enablingJavaScript in, 13

classesdeleting, 137names, searching DOM

objects, 60toggling, 137, 139

click() method, 110closest elements,

retrieving, 77closing windows, 49code

blocks, adding, 30dynamic programming.

See dynamic programming

initialization, adding, 100JavaScript

adding to HTML documents, 3

consoles, 44loading from

external files, 4overview of, 2

mouse-click-handling,adding, 115

collapsible elements, divid-ing content into, 326-327

colors, modifying, 131-132

browsers344

Page 37: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

combiningarrays, 26strings, 23

communication,asynchronous, 253-254

complete function, 229-230components, dates, 39conditional blocks of code,

adding, 30configuring

browser developmenttools, 12-13

cookie values, 53CSS properties, 130-139default mobile

settings, 301DOM element

properties, 126-129hidden form

attributes, 166select inputs, 164-165selected option in radio

groups, 162text

input values, 160status bars, 48

timers, 55-57consoles, JavaScript, 44content

auxiliary, adding to panels, 328

HTML elements, select-ing based on, 66

parent, appending elements, 141

web pagesadding elements,

179-183appending rows to

tables, 189-191building dynamically,

177deleting elements,

184-185HTML elements, 178HTML5 canvas

graphics, 197-199image galleries,

193-196inserting items into

lists, 191-193select form

elements, 186-188Content Discovery

Networks. See CDNscontent tooltip, 223converting

DOM objects intojQuery objects, 84

numbers to strings, 22strings to numbers, 23

coordinates, gettingmouse, 115

cross-domain requests,AJAX, 254

.css() method, 130CSSs (Cascading Style

Sheets), 7animating, 228-229elements, 130-139theme swatches, 295

CSSs (Cascading Style Sheets) 345

Page 38: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

current date and time,getting, 37

current hashes,searching, 45

current location details,45-47

current location of webpages, 48

customizing. See alsoconfiguring

forms, 334-336, 340popups, 329-332tables, 333

D

.data() method, 166data types, AJAX, 256-259Date object, 36-40dateFormat option, 213datepicker element,

attaching, 212-215dates, components, 39dblclick() method, 110debugging JavaScript

consoles, 44default behavior,

stopping, 109default mobile settings,

configuring, 301defining

functions, 20variables, 16viewport meta tags, 300

delay timers, adding, 56

delaying animation, 233deleting

classes, 137elements to elements,

184-185event handlers

JavaScript, 104jQuery, 106

items from arrays, 27objects, 91

deltas, formatting time, 39descendent elements,

searching, 78detecting

changes to text, 119items in arrays, 27mobile screen size, 294

Developer Tools (InternetExplorer), 13

developmentbrowser tools,

configuring, 12-13jQuery Mobile, 9-12

devices, Mobile, 9-12disabling form elements,

167-169, 335dividers, adding to lists, 324dividing content into

collapsible elements,326-327

Document Object Model.See DOM

documents, addingJavaScript to HTML, 3

current date and time, getting346

Page 39: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

DOM (Document ObjectModel), 5

elementsadding, 91configuring proper-

ties, 126-129content, 139-141

objects, 60-61, 84downloading jQuery UI

libraries, 201-202dragging/dropping

elements, 205-212droppable widget

options, 208duration function, 229-230dynamic programming

formscheck box state,

161-162disabling elements,

167-169elements, 159forcing focus

to/away from elements, 172-174

hidden attributes, 166managing submis-

sions, 175radio inputs, 162select values,

164-165showing/hiding

elements, 170-172text input values, 160

web pages, 177adding elements,

179-183adjusting opacity,

146-149appending rows to

tables, 189-191CSS properties,

130-139deleting elements,

184-185DOM element

properties, 126-129element content,

139-141hiding/viewing

elements, 144-146HTML elements, 178HTML5 canvas

graphics, 197-199image galleries,

193-196inserting items into

lists, 191-193modifying, 125modifying layouts,

143repositioning

elements, 152-153,156

resizing elements,149, 152

select form elements, 186-188

stacking elements,156-158

dynamic programming 347

Page 40: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

E

.each() method, 85easing function, 229-230effects, animation, 227-228

CSS settings, 228-229delaying, 233.hide() method, 242moving elements,

248-250queues, 231resizing images,

246-248.show() method, 243sliding toggles, 239-242stopping, 232-233.toggle() method,

243-245visibility, 234-238

elementsappending, 141children, retrieving, 77content, 139-141CSS properties,

130-139descendent,

searching, 78DOM, 5

adding, 91configuring

properties, 126-129fading, 239, 242forms, 159

adding, 336check box state,

161-162creating select,

186-188

disabling, 167-169,335

forcing focusto/away from elements, 172-174

hidden attributes, 166managing submis-

sions, 175radio inputs, 162refreshing, 336select values,

164-165showing/hiding,

170-172text input values, 160

HTMLadding, 179-183deleting, 184-185jQuery, 178

moving, animating,248-250

UIsadding, 201applying sliders,

215-219attaching datepicker,

212-215coding tooltips,

223-225creating menus,

220-222downloading

libraries, 201-202dragging/dropping,

205-212implementing auto-

complete, 203-205

.each() method348

Page 41: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

web pageshiding/viewing,

144-146loading HTML into,

269-271repositioning,

152-156resizing, 149-152stacking, 156-158

enablingDeveloper Tools on

Internet Explorer, 13JavaScript in Chrome, 13

.eq (index) filter, 92equality, objects, 29event handlers

global, 285swipe, 310, 314

event.preventDefault()method, 109

event.stopPropagation()method, 109

eventsbrowsers

adding event han-dlers, 99-106

forms, 122-123keyboards, 118-120managing, 107-110mouse, 115-118objects, 111-114overview of, 96types, 96, 99

draggable widget, 207droppable widget, 209

mobile, 295-297reset, 175submit, 175

existingObject, 180external files, loading from

JavaScript, 4

F

fadinganimation elements

in/out, 234-235elements, 239-242to levels of opacity, 236

filesaccessing, 6JavaScript, loading from

external, 4paths, viewing, 46web pages, loading, 5-6

.filter(filter) method, 92filters

object results, 92-94selectors, applying, 74

finding. See searchingFirefox, installing Firebug, 13.first() method, 93focus, modifying, 122.focus() method, 173fonts, modifying, 136footers, mobile web

pages, 304for() loops, 31forcing focus to/away from

form elements, 172-174

forcing focus to/away from form elements 349

Page 42: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

formattingarrays, 18back buttons, 309dates, 36-40HTML

adding elements,179-183

deleting elements,184-185

elements, 178image galleries, 193-196listviews, 320-325menus, 220-222mobile pages, 302-304navbars, 314objects, 19popup windows, 50-51strings, modifying,

21-25text, input values, 160time

deltas, 39strings, 38

tooltips, 223-225forms

elements, 159adding, 336check box state,

161-162creating select,

186-188disabling, 167-169,

335forcing focus

to/away from elements, 172-174

hidden attributes, 166managing submis-

sions, 175radio inputs, 162refreshing, 336select values,

164-165showing/hiding,

170-172text input values, 160

events, 122-123HTML elements, select-

ing based on, 71mobile, adding,

334-336, 340functionality, AJAX, 285-289functions

addEventListener(), 103adjValues(), 197calling, 20complete, 229-230defining, 20duration, 229-230easing, 229-230handler, 105power, applying, 35queue, 230removeEventListener()

function, 104renderSpark(), 197trigonometric,

applying, 35

formatting350

Page 43: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

G

galleries, formatting image,193-196

generating random numbers, 32

GET requests, AJAX, 255,262-264

.get() method, 84JSON, handling, 271-274XML, handling, 274, 277

.getScript() method, 256getting

CSS properties, 130-139DOM element

properties, 126-129Elements, content,

139-141event target objects, 114hidden form

attributes, 166mouse coordinates, 115select inputs, 164-165selected option in radio

groups, 162text input values, 160

global event handlers, 285global setup, modifying, 285graphics, HTML5 canvas,

197-199grids, layouts, 316-320groups, getting/setting

radio options, 162

H

handlersfunctions, 105events

adding, 99swipe, 310-314

global event, 285handling

eventsforms, 122-123keyboards, 118-120mouse, 115-118

JSON data, 271-274selection changes, 123text data (AJAX), 257XML data, 274-277

.has(selector or element)method, 93

hashes, current, 45headers, mobile web

pages, 304hidden form attributes, 166.hide() method, 144,

170, 242hiding

elements, web pages,144-146

form elements,170-172

labels, 335hierarchies, selecting

based on HTML elements, 68

history, navigatingbrowsers, 49

history, navigating browsers 351

Page 44: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

hosts, searching names, 46HTML (Hypertext Markup

Language)elements

accessing, 59adding, 179-183appending/

prepending text,140

chaining object operations, 75-76

deleting, 184-185getting content

of, 140jQuery, 178navigating objects,

76-82repositioning,

152-156resizing, 149, 152searching, 59-68,

71-74stacking, 156-158

event handlers,assigning in, 101

JavaScript, adding to, 3response data, 259

HTML5 canvas graphics,196-199

.html() method, 140

I

ID, searching DOM objects, 60

imagesgalleries, creating,

193-196

resizing, animating,246-248

source files,modifying, 128

transitions, adding,237-238

implementingautocomplete, 203-205low-level AJAX requests,

287-289mobile sites with

multiple pages,306-314

searchable lists, 325split button lists, 324

initialization code,adding, 100

innerHeight, 47innerWidth, 47input

autocomplete, imple-menting, 203-205

radio, 162select, 164-165text values, 160

inserting into middle ofelement’s content, 181

installing Firebug onFirefox, 13

interfacesbrowser development

tools, configuring,12-13

loading, 9navigating, 7

Internet Explorer, enablingDeveloper Tools, 13

hosts, searching names352

Page 45: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

.is() method, 161-163items

arraysdeleting, 27detecting, 27

lists, 191-193tooltip, 223

iteratingarrays, 31jQuery objects, 85-86through object

properties, 31

J

JavaScriptAJAX from, 261-267arrays

creating, 18manipulating, 25-27

Chrome, enabling in, 13consoles, 44Date object, 36-40event handlers

adding, 103deleting, 104

events, 96, 99adding page load

event handlers, 99managing, 107-110

external files, loadingfrom, 4

functions, defining, 20GET requests, sending

from, 262-264

HTMLadding to

documents, 3searching elements,

59-61jQuery, accessing, 6logic, applying, 29-31math operations, 31-35objects, creating, 19on-demand, 255overview of, 2POST requests, sending

from, 264, 267strings, manipulating,

21-25syntax, 15variables, defining, 16

JavaScript Object Notation.See JSON

.join() method, 27jQuery

AJAX from, 267-289animation, 227-228

CSS settings,228-229

delaying, 233.hide() method, 242queues, 231.show() method, 243sliding toggles,

239-242stopping, 232-233.toggle() method,

243-245visibility, 234-238

jQuery 353

Page 46: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

event handlersadding, 105deleting, 106

events, 96, 99HTML elements, 178initialization code, 100JavaScript, accessing, 6Mobile, 9-12mobile web sites, 291

applying grid layouts, 316-320

building web pages,302-304

creating navbars, 314customizing popups,

329, 332dividing into

collapsible ele-ments, 326-327

formatting listviews,320-325

forms, 334-340implementing with

multiple pages,306-314

overview of, 291-300tables, 333viewing panels, 328

objectsadding DOM

elements to, 91applying.map()

method, 87-88assigning data

values to, 89chaining operations,

75-76

converting DOMobjects into, 84

deleting, 91filtering results,

92-94getting, 84iterating, 85-86modifying, 83navigating to select

elements, 76-82overview of, 4UIs

accessing libraries, 7adding, 201applying sliders,

215-219attaching datepicker,

212-215coding tooltips,

223-225creating menus,

220-222downloading

libraries, 201-202dragging/dropping,

205-212implementing auto-

complete, 203-205loading, 9navigating, 7

web pages, loading, 5-6jQuery Selector, searching

HTML elements, 61-74JSON (JavaScript Object

Notation)handling, 271-274response data, 257-258

jQuery354

Page 47: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

JSON.parse() method, 258JSONP (JSON with

Padding), 255

K–L

keyboard events, 118-120keys, pressing, 120keywords, 17, 96, 99

labels, adding/hiding, 335languages

JavaScriptadding to HTML

documents, 3loading from

external files, 4overview of, 2

syntax, 15.last() method, 93layouts

grids, applying,316-317, 320

web pagesadjusting opacity,

146-149hiding/viewing

elements, 144-146modifying, 143repositioning

elements,152-153, 156

resizing elements,149-152

stacking elements,156-158

length, strings, 22levels, tolerance, 208libraries

accessing, 7CDNs, loading, 5jQuery Mobile, 291

applying grid layouts, 316-320

building web pages,302-304

creating navbars, 314customizing popups,

329-332dividing into

collapsible ele-ments, 326-327

formatting listviews,320-325

forms, 334-340implementing with

multiple pages,306-314

overview of, 291-300tables, 333viewing panels, 328

jQuery UI, adding,201-202

loading, 9Mobile, 9-12

links, modifying locations, 127

listsdividers, adding, 324items, inserting into,

191-193nesting, 322

lists 355

Page 48: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

searchable, implement-ing, 325

split button, 324listviews, formatting,

320-325.load() method, 101loading

HTML into page elements, 269-271

JavaScript from external files, 4

jQuery in web pages,5-6

libraries, 5, 9Mobile, 12mobile pages without

displaying, 299.loadPage() method, 298location.reload()

method, 44locations

current location, 45-47links, modifying, 127web pages, 47-48

logic, applying, 29-31loops

for(), 31while(), 30

low-level AJAX requests,287-289

M

managingevents, 107-110form submissions, 175

manipulatingarrays, 25-27cookies, 52-55strings, 21-25

.map() method, applying,87-88

Math object, 31-35max option, 216maximum numbers in

sets, 34menus, formatting,

220-222meta tags, defining

viewports, 300methods

.animate(), 228-229

.attr(), 126, 166autocomplete, 203.blur(), 173.changePage(), 298click(), 110.css(), 130.data(), 166.datepicker(), 213dblclick(), 110.delay(), 234.each(), 85event.preventDefault(),

109event.stopPropagation(),

109.filter(filter), 92.first(), 93.focus(), 173

lists356

Page 49: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

.get()JSON data, 271-274XML data, 274, 277

.get([index]), 84

.getScript(), 256

.has(selector or element), 93

.hide(), 144, 170, 242

.html(), 140

.is(), 161-163

.join(), 27JSON.parse(), 258.last(), 93.load(), 101.loadPage(), 299location.reload(), 44.map(), 87-88.not(filter) method, 94.off(), 106.offset(), 153.on(), 105onloadHandler(), 100pop(), 27.position(), 153.post(), 278-281.prop(), 126, 166push(), 18.ready(), 101.remove(), 184removeAttr(), 162setTimeout(), 197.show(), 144, 170, 243sort(), 28.slice(start, [end]), 94

.slideToggle(), 239

.toggle(), 243, 245

.toLowerCase(), 24

.toUpperCase(), 24

.val(), 160, 164middle of element’s

content, inserting into, 181minimum numbers in

sets, 33Mobile (jQuery), 9-12mobile web sites

(jQuery), 291overview of, 291-300web pages

applying grid layouts, 316-320

building, 302-304creating navbars, 314customizing popups,

329-332dividing into

collapsible elements, 326-327

formatting listviews,320-325

forms, 334-340implementing with

multiple, 306-314tables, 333viewing panels, 328

modifyingcheck box state,

161-162colors, 131-132cookies, 52-55

modifying 357

Page 50: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

elementsapplying sliders,

215-219content, 139-141

focus, 122fonts, 136global setup, 285image source files, 128link locations, 127mobile web pages, 298objects, 83

adding DOM elements to, 91

applying.map()method, 87-88

assigning data values to, 89

converting DOMobjects into, 84

deleting, 91filtering results,

92-94getting, 84iterating, 85-86

radio inputs, 162select inputs, 164-165selections, 123strings, 21-25text, detecting, 119web pages

adjusting opacity,146-149

CSS properties,130-139

DOM element prop-erties, 126-129

dynamic program-ming, 125

element content,139-141

hiding/viewing elements, 144, 146

layouts, 143repositioning

elements,152-153, 156

resizing elements,149-152

stacking elements,156-158

mousecoordinates, getting, 115events, 115-118mouse-click-handling

code, adding, 115mouseout events, 116mouseover events, 116

movingelements, animating,

248-250HTML elements,

152-156

N

namesattributes, 166classes, searching

DOM objects, 60hosts, searching, 46tags, searching DOM

objects, 61navbars, formatting, 314

modifying358

Page 51: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

navigatingbrowsers, 43

accessing, 47-49adding timers,

55-57applying JavaScript

consoles, 44current location

details, 45-47history, 49modifying cookies,

52-55popup windows,

50-51redirecting web

pages, 44reloading web

pages, 44sizing screens, 45

jQuery Mobile library,291-300

objects to select elements, 76-82

UIs, 7accessing libraries, 7loading, 9

navigation buttonsadding, 307-314positioning, 308

nested lists, applying, 322networks, CDNs, 5.not(filter) method, 94numberOfMonths

option, 213numbers

dates, formatting, 36-40maximum in sets, 34

minimum in sets, 33random, generating, 32rounding, 33strings, converting, 22

O

objectscreating, 19Date, 36-40DOM, 60-61elements, navigating to

select, 76-82equality, 29events, 111-114existing, 180getting, 84jQuery

adding DOM elements to, 91

applying map()method, 87-88

assigning data values to, 89

converting DOMobjects into, 84

deleting, 91filtering results,

92-94iterating, 85-86

location, 45-47Math, 31, 34-35modifying, 83operations, chaining,

75-76properties, iterating, 31

objects 359

Page 52: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

strings, special characters, 21

window.XMLHttpRequest,261

windows, 47-49XMLHttpRequest, 261

.off() method, 106

.offset() method, 153

.on() method, 105on-demand JavaScript, 255onloadHandler()

method, 100onSelect option, 213opacity

adjusting, 146-149fading to levels of, 236

opening windows, 49operations

math, 31-35objects, chaining, 75-76

optionsanimation, 229draggable widget, 205droppable widget, 208radio groups,

getting/setting, 162orientation options, 216

P

pageselements, loading

HTML into, 269-271load event handlers,

adding, 99panels, viewing, 328

parentscontent, appending

elements, 141searching, 80

paths, viewing files, 46physical events, 107. See

also eventspop() method, 27popups

creating, 50-51applying, 329, 332

position tooltip, 223.position() method, 153positioning

HTML elements,152-156

navigation buttons, 308parents

retrieving, 80searching, 80

POST requests, AJAX, 255,264, 267

.post() method, 278-281power functions,

applying, 35prepending

content, 179text, 140

pressing keys, 120previous siblings, 81programming

dynamic, 125. See alsodynamic programming

JavaScriptadding to HTML

documents, 3

objects360

Page 53: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

loading from external files, 4

overview of, 2syntax, 15

.prop() method, 126, 166propagation, stopping

event, 109properties

CSS, getting/setting,130-139

DOM, configuring elements, 126-129

objects, iterating, 31push() method, 18

Q–R

queries, retrieving strings, 46queues

animating, 231functions, 230

radio inputs, 162random numbers,

generating, 32range option, 216.ready() method, 101recurring timers, adding, 57redirecting web pages, 44refreshing form

elements, 336reloading web pages, 44.remove() method, 184removeAttr() method, 162removeEventListener()

function, 104renderSpark() function, 197

replacingstrings, 25text, 141

repositioning HTML elements, 152-156

requests, AJAXcross-domain, 254GET/POST, 255JavaScript, 261-267jQuery, 267-289response data types,

256-259reset event, 175resizing

HTML elements,149-152

images, animating,246-248

responses, AJAXjQuery, 282-284data types, 256-259

results, filtering objects,92-94

retrieving, 79children elements, 77cookie values, 53parents, positioning, 80previous siblings, 81query strings, 46siblings, 79-82

right-click, applying,117-118

rounding numbers, 33rows, appending tables,

189-191

rows, appending tables 361

Page 54: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

S

screensmobile, detecting

size, 294sizing, 45

searchable lists,implementing, 325

searchingancestors, 80characters, 22current hashes, 45current location of web

pages, 48descendent elements,

78host names, 46HTML

chaining object operations, 75-76

elements, 59-68,71-74

parents, 80strings, 25

secure locations, viewingfrom, 47

select form elements,creating, 186-188

select inputs, 164-165selecting

elements, navigatingobjects to, 76-82

modifying, 123selectors

applying, 62filters, 74

sendingGET requests from

JavaScript, 262-264POST requests from

JavaScript, 264-267servers

AJAXasynchronous

communication,253-254

cross-domainrequests, 254

GET/POST requests,255

JavaScript, 261-267jQuery, 267-289overview of, 251-252response data

types, 256-259updating, 278-281

setsmaximum numbers in, 34minimum numbers in, 33

setTimeout() method, 197settings. See also

configuringCSS

animating, 228-229properties, 130-139

DOM element properties, 126-129

hidden form attributes, 166

select inputs, 164-165selected option in radio

groups, 162text input values, 160

screens362

Page 55: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

setup, modifying global, 285.show() method, 144,

170, 243showButtonPanel option, 213showOn option, 213siblings

previous, 81retrieving, 79-82

sizingscreens, 45, 294web pages, 47

.slice(start, [end]) method, 94

slide option, 216.slideToggle() method, 239sliders, applying,

215-216, 219sliding toggles, 239-242sorting arrays, 28source files, modifying

images, 128special characters, 21special effects, animation,

227-228CSS settings, 228-229delaying, 233.hide() method, 242moving elements,

248-250queues, 231resizing images,

246-248.show() method, 243sliding toggles,

239-242stopping, 232-233

.toggle() method,243-245

visibility, 234-238splicing

arrays, 26strings, 24

split button lists, 324splitting strings, 24stacking HTML elements,

156-158state, modifying check

boxes, 161-162status bars, configuring

text, 48step function, 231stopping

animation, 232-233default behavior, 109event propagation, 109

stringscase modifying, 24combining, 23dates, formatting, 37manipulating, 21-25numbers, converting, 22queries, retrieving, 46replacing, 25searching, 25splicing, 24splitting, 24substrings, checking

for, 25time, formatting, 38

submit event, 175submitting forms,

managing, 175

submitting forms, managing 363

Page 56: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

substrings, checking for, 25swatches, theme, 295swipe event handlers,

310, 314syntax, JavaScript, 15

T

tab-separated strings,creating arrays from, 27

tablesadding, 333rows, appending,

189-191tags, searching DOM

objects, 61targets, getting event

objects, 114text

AJAX, 257appending/

prepending, 140autocomplete, imple-

menting, 203-205input values, 160modifying, detecting, 119replacing, 141status bars,

configuring, 48theme swatches, 295time

current, getting, 37deltas, formatting, 39strings, formatting, 38

timers, adding, 55-57.toggle() method, 243-245

togglingclasses, 137-139element visibility

on/off, 235tolerance levels, 208.toLowerCase() method, 24tools

browser development,configuring, 12-13

JavaScript consoles, 44tooltips, formatting,

223-225.toUpperCase() method, 24transitions

adding, 308animation, 237-238

triggeringanimation, 232events manually, 110

trigonometric functions,applying, 35

types of events, 96, 99

U

UIs (user interfaces)elements

adding, 201applying sliders,

215-219attaching datepicker,

212-215coding tooltips,

223-225creating menus,

220-222

substrings, checking for364

Page 57: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

downloadinglibraries, 201-202

dragging/dropping,205-212

implementing auto-complete, 203-205

libraries, accessing, 7loading, 9

updating servers, 278-281user interaction, adding,

179-183user interfaces. See UIs

V

.val() method, 160, 164value option, 216values

absolute, calculating, 34attributes, 166cookies, configuring, 53objects, assigning, 89text input, 160

var keyword, 17variables

accessing, 16defining, 16

viewingelements, web pages,

144-146file paths, 46form elements,

170-172listviews, formatting,

320-325

mobile pages,loading without displaying, 299

panels, 328web pages, 47web sites on mobile

devices, 294viewports, defining meta

tags, 300visibility

animation, 234-238HTML elements,

selecting based on, 72

W

web forms, 159. See alsoforms

web pages. See also HTMLcontent

adding elements,179-183

appending rows totables, 189-191

building dynamically,177

deleting elements,184-185

HTML elements, 178HTML5 canvas

graphics, 197-199image galleries,

193-196inserting items into

lists, 191-193select elements,

186-188

web pages 365

Page 58: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

current location of, 48dynamic programming

CSS properties,130-139

DOM element properties,126-129

element content,139-141

modifying, 125events

adding event handlers, 99-106

forms, 122-123keyboards, 118-120managing, 107-110mouse, 115-118objects, 111-114overview of, 96types, 96-99

history, navigating, 49HTML, loading into,

269-271jQuery, loading, 5-6layouts

adjusting opacity,146-149

hiding/viewing elements, 144-146

modifying, 143repositioning

elements, 152-156resizing elements,

149-152stacking elements,

156-158

mobile, building,302-304

navbars, formatting, 314redirecting, 44reloading, 44secured locations,

viewing from, 47UI elements

adding, 201applying sliders,

215-219attaching datepicker,

212-215coding tooltips,

223-225creating menus,

220-222downloading

libraries, 201-202dragging/dropping,

205-212implementing

autocomplete,203-205

viewing, 47web servers, AJAX

asynchronous commu-nication, 253-254

cross-domain requests, 254

GET/POST requests,255

JavaScript, 261-267jQuery, 267-289overview of, 251-252response data types,

256-259

web pages366

Page 59: jQuery and JavaScript Phrasebookptgmedia.pearsoncmg.com/images/9780321918963/samplepages/...Many of the designations used by manufacturers and sellers to distinguish their products

web sites, mobile (jQuery),291. See also web pages

applying grid layouts,316-320

building web pages,302-304

creating navbars, 314customizing popups,

329-332dividing into collapsible

elements, 326-327formatting listviews,

320-325forms, 334-340implementing with

multiple pages,306-314

overview of, 291-300tables, 333viewing panels, 328

while() loops, 30widgets

datepicker, attaching,212-215

draggable/droppable,205-212

menus, creating,220-222

tooltips, creating,223-225

window.XMLHttpRequestobject, 261

windowsclosing, 49objects, 47-49opening, 49popup, creating, 50-51

X–Z

XML (Extensible MarkupLanguage)

handling, 274, 277response data, 259

XMLHttpRequest object, 261

z-index, 157

z-index 367