JavaScript and jQuery The Missing Manual 2nd Edition

The purpose of this book, then, is to serve as the manual that should have come with JavaScript. In this book’s pages, you’ll find step-by-step instructions for using JavaScript to create highly interactive web pages.


David Sawyer McFarland


538 Pages

57163 Reads

64 Downloads

English

PDF Format

16.3 MB

Java Script

Download PDF format


  • David Sawyer McFarland   
  • 538 Pages   
  • 18 May 2015
  • Page - 1

    read more..

  • Page - 2

    read more..

  • Page - 3

    read more..

  • Page - 4

    read more..

  • Page - 5

    read more..

  • Page - 6

    read more..

  • Page - 7

    read more..

  • Page - 8

    read more..

  • Page - 9

    read more..

  • Page - 10

    read more..

  • Page - 11

    read more..

  • Page - 12

    read more..

  • Page - 13

    read more..

  • Page - 14

    read more..

  • Page - 15

    read more..

  • Page - 16

    read more..

  • Page - 17

    read more..

  • Page - 18

    read more..

  • Page - 19

    read more..

  • Page - 20

    2 javascript & jquery: the missing manual What Is JavaScript? Another one of JavaScript’s main selling points is its immediacy. It lets web pages respond instantly to actions like clicking a link, filling out a form, or merely moving the mouse around the screen. JavaScript doesn’t suffer from the frustrating delay associated with server-side programming read more..

  • Page - 21

    3 introduction What Is jQuery? Note: After Netscape introduced JavaScript, Microsoft introduced jScript, their own version of JavaScript included with Internet Explorer. Fortunately the worst of those days is nearly gone and contemporary browsers like Firefox, Safari, Chrome, Opera, and Internet Explorer 9 have standardized much of the way they handle JavaScript, making read more..

  • Page - 22

    4 javascript & jquery: the missing manual HTML: The Barebones Structure That’s where jQuery comes in. jQuery is a JavaScript library intended to make Java Script programming easier and more fun. A JavaScript library is a complex JavaScript program that both simplifies difficult tasks and solves cross-browser problems. In other words, jQuery solves the two biggest read more..

  • Page - 23

    5 introduction HTML: The Barebones Structure <!DOCTYPE html> <html> <head> <meta charset=utf-8> <title>Hey, I am the title of this web page.</title> </head> <body> Hey, I am some body text on this web page. </body> </html> It may not be exciting, but this example has all the basic elements a web page needs. This page begins with a read more..

  • Page - 24

    6 javascript & jquery: the missing manual HTML: The Barebones Structure commands. Sandwiched between brackets, these tags are instructions that tell a web browser how to display the web page. Tags are the “markup” part of the Hypertext Markup Language. The starting (opening) tag of each pair tells the browser where the instruction begins, and the ending tag read more..

  • Page - 25

    7 introduction CSS: Adding Style to Web Pages UP TO SPEED Validating Web Pages As mentioned on page 5, a web page’s doctype identifies which type of HTML or XHTML you used to create the web page. The rules differ subtly depending on type: For ex- ample, unlike HTML 4.01, XHTML doesn’t let you have an unclosed <p> tag, and requires that all tag names and at- read more..

  • Page - 26

    8 javascript & jquery: the missing manual CSS: Adding Style to Web Pages create a CSS rule to make all <h1> tags a ppear 36 pixels tall, in the Verdana font, and in orange. CSS can do more powerful stuff, too, like add borders, change margins, and even control the exact placement of a page element. When it comes to JavaScript, some of the most read more..

  • Page - 27

    9 introduction CSS: Adding Style to Web Pages • Declaration Block. The code following the selector includes all the formatting options you want to apply to the selector. The block begins with an opening brace ({) and ends with a closing brace (}). • Declaration. Between the opening and closing braces of a declaration, you add one or more read more..

  • Page - 28

    10 javascript & jquery: the missing manual Software for JavaScript Programming Software for JavaScript Programming To create web pages made up of HTML, CSS, and JavaScript, you need nothing more than a basic text editor like Notepad (Windows) or TextEdit (Mac). But after typing a few hundred lines of JavaScript code, you may want to try a program better read more..

  • Page - 29

    11 introduction About This Book Commercial Software Commercial website development programs range from inexpensive text editors to complete website construction tools with all the bells and whistles: • EditPlus (Windows, www.editplus.com) is an inexpensive ($35) text editor that includes syntax-coloring, FTP, auto-completion, and other wrist-saving features. • CoffeeCup read more..

  • Page - 30

    12 javascript & jquery: the missing manual About This Book Likewise, you’ll find good documentation on jQuery at http://docs.jquery.com/ Main_Page. But it’s written by programmers for programmers, and so the explana- tions are mostly brief and technical. And while jQuery is generally more straightfor- ward than regular JavaScript programming, this book will teach you read more..

  • Page - 31

    13 introduction About This Book way: You could build a house by cutting down and milling your own lumber, con- structing your own windows, doors, and doorframes, manufacturing your own tile, and so on. That “do it yourself ” approach is common to a lot of JavaScript books. But who has that kind of time? This book’s approach is more like read more..

  • Page - 32

    14 javascript & jquery: the missing manual The Very Basics • Part 5, Troubleshooting, Tips, and Tricks, takes you past the basics, covering more complex concepts. You’ll learn more about how to use jQuery effectively, as well as delve into advanced jQuery functions. This part of the book also helps you when nothing seems to be working: when your read more..

  • Page - 33

    15 introduction About the Online Resources • Operating-system basics. This book assumes that you know how to open a pro- gram, surf the web, and download files. You should know how to use the Start menu (Windows) and the Dock or Apple menu (Macintosh), as well as the Control Panel (Windows), or System Preferences (Mac OS X). If you’ve mastered read more..

  • Page - 34

    16 javascript & jquery: the missing manual About the Online Resources Living Examples As you read the book’s chapters, you’ll encounter a number of living examples— step-by-step tutorials that you can build yourself, using raw materials (like graphics and half-completed web pages) that you can download from either www.sawmac .com/js2e or from this book’s Missing read more..

  • Page - 35

    17 introduction About the Online Resources Safari® Books Online Safari® B ooks Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly. With a subscription, you can read any page and watch any video from our library online. Read books on your read more..

  • Page - 36

    read more..

  • Page - 37

    1 Part One: Getting Started with JavaScript Chapter 1: Writing Your First JavaScript Program Chapter 2: The Grammar of JavaScript Chapter 3: Adding Logic and Control to Your Programs read more..

  • Page - 38

    read more..

  • Page - 39

    21 chapter 1 Writing Your First JavaScript Program By itself, HTML doesn’t have any smarts: It can’t do math, it can’t figure out if someone has correctly filled out a form, and it can’t make decisions based on how a web visitor interacts with it. Basically, HTML lets people read text, look at pictures, and click links to move to other read more..

  • Page - 40

    22 javascript & jquery: the missing manual Introducing Programming Figure 1-1: Java Script lets web pages respond to visitors. On Amazon.com, mousing over the “Gifts & Wish Lists” link opens a tab that floats above the other content on the page and offers additional options. Note: Actually, HTML5 does add some smarts to HTML—including basic form validation. But since not all read more..

  • Page - 41

    23 chapter 1: writing your first javascript program Introducing Programming !=) and full of unfamiliar words (var, null, else if). It’s like staring at a foreign lan- guage, and in many ways, learning a programming language is a lot like learning another language. You need to learn new words, new punctuation, and understand how to put them together so read more..

  • Page - 42

    24 javascript & jquery: the missing manual Introducing Programming At first, you’ll probably find JavaScript programming frustrating—you’ll sp end a lot of your time tracking down errors you made when typing the script. Also, you might find some of the concepts related to programming a bit hard to follow at first. But don’t worry: If you’ve tried read more..

  • Page - 43

    25 chapter 1: writing your first javascript program How to Add JavaScript to a Page FREQUENTLY ASKED QUESTION Compiled vs. Scripting Languages JavaScript is called a scripting language. I’ve heard this term used for other languages like PHP and ColdFusion as well. What’s a scripting language? Most of the programs running on your computer are written using languages that are read more..

  • Page - 44

    26 javascript & jquery: the missing manual How to Add JavaScript to a Page <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/ html4/strict.dtd"> <html> <head> <title>My Web Page</title> <script type="text/javascript"> </script> </head> The <script> tag’ s type attribute indicates the format and the type of script that read more..

  • Page - 45

    27 chapter 1: writing your first javascript program How to Add JavaScript to a Page the closing </body> tag—this approach makes sure the page is loaded and the visitor sees it before running any JavaScript. External JavaScript Files Using the <script> tag as discussed in the previous section lets you add JavaScript to a single page. But many times you’ll read more..

  • Page - 46

    28 javascript & jquery: the missing manual How to Add JavaScript to a Page UP TO SPEED URL Types When attaching an external JavaScript file to a web page, you need to specify a URL for the src attribute of the <script> tag. A URL or Uniform Resource Locator is a path to a file located on the web. There are three types of paths: absolute path, read more..

  • Page - 47

    29 chapter 1: writing your first javascript program Your First JavaScript Program In addition, you can attach external JavaScript files and add a JavaScript program to the same page like this: <!doctype html> <html> <head> <meta charset="UTF-8"> <title>My Web Page</title> <script src="navigation.js"></script> <script read more..

  • Page - 48

    30 javascript & jquery: the missing manual Your First JavaScript Program 1. In your favorite text editor, open the file hello.html. This file is located in the chapter01 folder in the MM_JAVASCRIPT2E folder you downloaded from www.sawmac.com/js2e. It’s a very simple HTML page, with an external cascading style sheet to add a little visual excitement. 2. Click in read more..

  • Page - 49

    31 chapter 1: writing your first javascript program Writing Text on a Web Page 6. Click the Alert box’s OK button to close it. When the Alert box disappears, the web page appears in the browser window. Tip: When you first start programming, you’ll be shocked at how often your JavaScript programs don’t seem to work…at all. For new programmers, the most common read more..

  • Page - 50

    32 javascript & jquery: the missing manual Writing Text on a Web Page Like the alert() function, document.write() is a JavaScript command that literal- ly writes out whatever you place between the opening and closing parentheses. In this case, the HTML <p>Hello worl d!</p> is added to the page: a paragraph tag and two words. 3. Save the page, and open read more..

  • Page - 51

    33 chapter 1: writing your first javascript program Attaching an External JavaScript File Attaching an External JavaScript File As discussed on page 27, you’ll usually put JavaScript code in a separate file if you want to use the same scripts on more than one web page. You can then instruct a web page to load that file and use the JavaScript inside read more..

  • Page - 52

    34 javascript & jquery: the missing manual Tracking Down Errors 6. Hit return to create a new line, and then type: $('body').hide().fadeIn(3000); This line does something magical: It makes the page’s content first disappear and then slowly fade into view over the course of 3 seconds (or 3000 milli- seconds). How does it do that? Well, that’s part of the read more..

  • Page - 53

    35 chapter 1: writing your first javascript program Tracking Down Errors Most web browsers are set up to silently ignore JavaScript errors, so you usually won’t even see a “Hey this program doesn’t work!” dialog box. (Generally, that’s a good thing, since you don’t want a JavaScript error to interrupt the experience of viewing your web pages.) So read more..

  • Page - 54

    36 javascript & jquery: the missing manual Tracking Down Errors Figure 1-4: Firefox’s JavaScript console identifies errors in your pro- grams. The console keeps a list of errors for previous pages as well, so pretty soon the list can get very long. Just click the Clear button to erase all the errors listed in the console. To show the JavaScript console, click the read more..

  • Page - 55

    37 chapter 1: writing your first javascript program Tracking Down Errors • Unterminated string literal. A string is a series of characters enclosed by quote marks (you’ll learn about these in greater detail on page 43). For example, ‘hello’ is a string in the code alert(‘hello’);. It ’s easy to forget either the opening or closing quote mark. • XXX read more..

  • Page - 56

    38 javascript & jquery: the missing manual Tracking Down Errors Figure 1-5: The Internet Explorer Developer Tools provide access to JavaScript errors that occur on a page, as well as a whole lot of other information. IE9’s Console displays error messages similar to those described for Firefox above. For example, “Unterminated string constant” is the same as Firefox’s read more..

  • Page - 57

    39 chapter 1: writing your first javascript program Tracking Down Errors Figure 1-6: Chrome sports a powerful set of developer tools that looks a lot like the ones you’ll find in Internet Explorer 9 and Safari. Accessing the Safari Error Console Safari’s error console is available from the Develop menu: Develop Show Er- ror Console (on the Mac, you can use the read more..

  • Page - 58

    40 javascript & jquery: the missing manual Tracking Down Errors Figure 1-7: The Safari Error Console displays the name of the JavaScript error, the file name (and location), and the line on which Safari encountered the error. Each tab or browser window has its own error console, so if you’ve al- ready opened the console for one tab, you need to choose Develop Error read more..

  • Page - 59

    41 chapter 2 The Grammar of JavaScript Learning a programming language is a lot like learning any new language: There are words to learn, punctuation to understand, and a new set of rules to master. And just as you need to learn the grammar of French to speak French, you must become familiar with the grammar of JavaScript to program JavaScript. read more..

  • Page - 60

    42 javascript & jquery: the missing manual Built-In Functions Note: Officially, putting a semicolon at the end of a statement is optional, and some programmers leave them out to make their code shorter. Don’t be one of them. Leaving off the semicolon makes reading your code more difficult and, in some cases, causes JavaScript errors. If you want to make your JavaScript read more..

  • Page - 61

    43 chapter 2: the grammar of javascript Types of Data Programming languages usually categorize information into different types, and treat each type in a different way. In JavaScript, the three most basic types of data are number, string, and Boolean. Numbers Numbers are used for counting and calculating; you can keep track of the number of days until summer read more..

  • Page - 62

    44 javascript & jquery: the missing manual Types of Data So, to pop-up an alert box with the message Warning, warning! you could write: alert('Warning, warning!'); or alert("Warning, warning!"); You’ll use strings frequently in your programming—when adding alert messages, when dealing with user input on web forms, and when manipulating the contents of a web page. read more..

  • Page - 63

    45 chapter 2: the grammar of javascript Variables is a Boolean value: Either the email address is valid (true) or it’s not (false). Depend- ing on the answer to the question, the page could respond in different ways. For example, if the email address is valid (true), then submit the form; if it is not valid (false), then display an error message and read more..

  • Page - 64

    46 javascript & jquery: the missing manual Variables Figure 2-1: The World’s Biggest Pac-Man ( http://worldsbiggestpacman .com/) uses JavaScript to create a Pac-Man game with thousands of mazes. The game tracks your current score and your high score (top) as well as the total number of Pac-dots eaten and other game statistics (right). These are all examples of variables since read more..

  • Page - 65

    47 chapter 2: the grammar of javascript Variables Table 2-1. Some words are reserved for use by JavaScript and the web browser. Avoid using them as variable names JavaScript keywords Reserved for future use Reserved for browser break abstract alert case boolean blur catch byte closed continue char document debugger class focus default const frames delete double history do enum innerHeight else export read more..

  • Page - 66

    48 javascript & jquery: the missing manual Variables In addition to these rules, aim to make your variable names clear and meaningful. Naming variables according to what type of data you’ll be storing in them makes it much easier to look at your programming code and immediately understand what’s going on. For example, score is a great name read more..

  • Page - 67

    49 chapter 2: the grammar of javascript Variables FREQUENTLY ASKED QUESTION Spaces, Tabs, and Carriage Returns in JavaScript JavaScript seems so sensitive about typos. How do I know when I’m supposed to use space characters, and when I’m not allowed to? In general, JavaScript is pretty relaxed about spaces, car- riage returns, and tabs. You can often leave out spaces or read more..

  • Page - 68

    50 javascript & jquery: the missing manual Working with Data Types and Variables Working with Data Types and Variables Storing a particular piece of information like a number or string in a variable is usu- ally just a first step in a program. Most programs also manipulate data to get new results. For example, add a number to a score to increase it, read more..

  • Page - 69

    51 chapter 2: the grammar of javascript Working with Data Types and Variables each line of code that uses the price. By using a variable, on the other hand, you can set the price of the product somewhere near the beginning of the program. Then, if the price ever changes, you only need to modify the one line of code that defines the product’s read more..

  • Page - 70

    52 javascript & jquery: the missing manual Working with Data Types and Variables In the last line of code above, the contents of the variable firstName are combined (or concatenated) with the contents of the variable lastName—the two are literally joined together and the result is placed in the variable fullName. In this example, the resulting string is read more..

  • Page - 71

    53 chapter 2: the grammar of javascript Working with Data Types and Variables That feature, known as automatic type conversion, can cause problems, however. For example, if a visitor answers a question on a form (“How many pairs of shoes would you like?”) by typing a number (2, for example), that input is treated like a string—‘2’. So you can read more..

  • Page - 72

    54 javascript & jquery: the missing manual Working with Data Types and Variables var score = 0; score = 100; However, you’ll frequently want to keep the value that’s in the variable and just add something to it or change it in some way. For example, with a game score, you never just give a new score—you always add or subtract from the read more..

  • Page - 73

    55 chapter 2: the grammar of javascript Tutorial: Using Variables to Create Messages The same rules apply when concatenating a string to a variable. For example, say you have a variable with a string in it and want to add another couple of strings onto that variable: var name = 'Franklin'; var message = 'Hello'; message = message + ' ' + name; As read more..

  • Page - 74

    56 javascript & jquery: the missing manual Tutorial: Using Variables to Create Messages 4. Below the two variable declarations, type: document.write('<p>'); As you saw in Chapter 1, the document.write() command adds text directly to a web page. In this case, you’re using it to write HTML tags to your page. You supply the command a string—‘<p>’—and it read more..

  • Page - 75

    57 chapter 2: the grammar of javascript Tutorial: Asking for Information Figure 2-2: While writing “Cookie Monster” may not be the reason you picked up a book on JavaScript, this script does demonstrate an important concept: how to create and use variables in JavaScript. Tutorial: Asking for Information In the last script, you saw how to create variables, but you read more..

  • Page - 76

    58 javascript & jquery: the missing manual Tutorial: Asking for Information you supply two strings separated by a comma between the parentheses. Figure 2-3 shows what happens to those two strings: The first string appears as the dialog box’s question (“What is your name?” in this example). Note: IE7 won’t let you use the prompt() method without enabling it read more..

  • Page - 77

    59 chapter 2: the grammar of javascript Arrays 4. Return to your text editor. Locate the second set of <script> tags a nd add the code in bold: <script> document.write('<p>Welcome ' + name + '</p>'); </script> Here you take advantage of the information supplied by the visitor. As with the script on page 55, you’re combining several read more..

  • Page - 78

    60 javascript & jquery: the missing manual Arrays var item1 = 'Xbox 360'; var item2 = 'Tennis shoes'; var item3 = 'Gift certificate'; But what if she wanted to add more items than that? You’d have to create more variables—item4, item5, and so on. And, because you don’t know how many items the visitor might want to buy, you really don’t know read more..

  • Page - 79

    61 chapter 2: the grammar of javascript Arrays you put the list of items between opening and closing brackets—[ ]. For example, to create an array containing abbreviations for the seven days of the week, you could write this code: var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; The brackets—[ ]—are very important; they tell the JavaScript read more..

  • Page - 80

    62 javascript & jquery: the missing manual Arrays Tip: To make the names line up as above, you’d type the first line—var authors = [ ‘Ernest Hemingway’,— hit Return, then press the space key as many times as it takes to line up the next value, ‘Charlotte Bronte’,. Accessing Items in an Array You can access the contents of a simple variable just by read more..

  • Page - 81

    63 chapter 2: the grammar of javascript Arrays Because the index number of the last item in an array is always one less than the total number of items in an array, you only need to know how many items are in an array to access the last item. Fortunately, this is an easy task since every array has a length property, which contains the read more..

  • Page - 82

    64 javascript & jquery: the missing manual Arrays You can also use an array’s push() command, which adds whatever you supply be- tween the parentheses to the end of the array. As with the length property, you apply push() by adding a period to the array’s name followed by push(). For example, here’s another way to add an item to the read more..

  • Page - 83

    65 chapter 2: the grammar of javascript Arrays So if each time the visitor clicks a song, the song’s name should go at the end of the playlist (so it will be the last song played), then use the push() method. Table 2-5. Various ways of adding elements to an array Method Original array Example code Resulting array Explanation .length property var p = read more..

  • Page - 84

    66 javascript & jquery: the missing manual Tutorial: Writing to a Web Page Using Arrays Deleting Items from an Array If you want to remove an item from the end or beginning of an array, use the pop() or shift() commands. Both commands remove one item from the array: The pop() command removes the item from the end of the array, while read more..

  • Page - 85

    67 chapter 2: the grammar of javascript Tutorial: Writing to a Web Page Using Arrays 2. Between the first set of <script> tags, type the bolded code: <script> var authors = [ 'Ernest Hemingway', 'Charlotte Bronte', 'Dante Alighieri', 'Emily Dickinson' ]; </script> This code comprises a single read more..

  • Page - 86

    68 javascript & jquery: the missing manual Tutorial: Writing to a Web Page Using Arrays 4. Return to your text editor and add these two lines of code below to your script: document.write('<p>The last author is <strong>'); document.write(authors[4] + '</strong></p>'); This step is pretty much the same as the previous one, except that you’re print- ing a read more..

  • Page - 87

    69 chapter 2: the grammar of javascript Tutorial: Writing to a Web Page Using Arrays 5. Return to your text editor and edit the code you just entered. Erase the 4 and add the bolded code in its place: document.write('<p>The last author is <strong>'); document.write(authors[authors.length-1] + '</strong></p>'); As you’ll recall from “Adding Items to an read more..

  • Page - 88

    70 javascript & jquery: the missing manual A Quick Object Lesson Figure 2-7: OK, Stan Lee may not be your idea of a literary giant, but at least he’s helping you learn how arrays work. A Quick Object Lesson So far in this book, you’ve learned that you can write something to a web page with the document.write() command, and to determine how many read more..

  • Page - 89

    71 chapter 2: the grammar of javascript A Quick Object Lesson The world of JavaScript is also filled with objects: a browser window, a document, a string, a number, and a date are just a few examples. Like real-world objects, Java- Script objects are also made up of different parts. In programming-speak, the parts of an object are called properties. The read more..

  • Page - 90

    72 javascript & jquery: the missing manual Comments Note: You’ve already encountered another object—called the window object—which represents the browser window itself. It’s basically the container object for a web page and everything else on the page. For example, alert() and prompt() are both methods of the window object and can be written like this: window.alert() and read more..

  • Page - 91

    73 chapter 2: the grammar of javascript Comments It’s easy to forget how a program works and why you wrote your code the way you did. Fortunately, most programming languages provide a way for programmers to leave notes for themselves or other programmers who might look through their code. JavaScript lets you leave comments throughout your code. If you’ve read more..

  • Page - 92

    74 javascript & jquery: the missing manual Comments Many programmers add a block of comments at the beginning of an external Java- Script file. These comments can explain what the script is supposed to do, identify the date the script was created, include a version number for frequently updated scripts, and provide copyright information. For example, at the read more..

  • Page - 93

    75 chapter 2: the grammar of javascript Comments The third line ends with a comment that indicates what you should see when you preview this code in a web browser. If you want to test the code that you read in this book by adding it to a web page and viewing it in a web browser, you can leave out comments like these when typing the read more..

  • Page - 94

    read more..

  • Page - 95

    77 chapter 3 Adding Logic and Control to Your Programs So far you’ve learned about some of JavaScript’s basic building blocks. But sim- ply creating a variable and storing a string or number in it doesn’t accomplish much. And building an array with a long list of items won’t be very useful un- less there’s an easy way to work your way read more..

  • Page - 96

    78 javascript & jquery: the missing manual Making Programs React Intelligently intelligently. You’ll use them countless times in your programming, but just to get a clear picture of their usefulness, here are a few examples of how they can come in handy: • Form validation. When you want to make sure someone filled out all of the required fields in a read more..

  • Page - 97

    79 chapter 3: adding logic and control to your programs Making Programs React Intelligently Conditional Statement Basics Conditional statements are also called “if/then” statements, because they perform a task only if the answer to a question is true: “If I have enough money, then I’ll go to the movies.” The basic structure of a conditional read more..

  • Page - 98

    80 javascript & jquery: the missing manual Making Programs React Intelligently In addition to > (gr eater than), there are several other operators used to compare numbers (see Table 3-1). Tip: Type two spaces (or press the Tab key once) before each line of JavaScript code contained within a pair of braces. The spaces (or tab) indent those lines and make it easier read more..

  • Page - 99

    81 chapter 3: adding logic and control to your programs Making Programs React Intelligently if (answer == 31) { alert('Correct. Saturn has 31 moons.'); } The double set of equal signs (==) isn’t a typo; it instructs the JavaScript interpreter to compare two values and decide whether they’re equal. As you learned in the last chapter, in JavaScript, a single read more..

  • Page - 100

    82 javascript & jquery: the missing manual Making Programs React Intelligently And you could add additional lines of JavaScript code between the braces as well— any code that should run if the condition is true. Adding a Backup Plan But what if the condition is false? The basic conditional statement in the previous section doesn’t have a backup plan for a read more..

  • Page - 101

    83 chapter 3: adding logic and control to your programs Making Programs React Intelligently if (answer == 31) { alert('Correct. Saturn has 31 moons.'); numCorrect = numCorrect + 1; } else { alert("Wrong! That's not how many moons Saturn has."); } This code sets up an either/or situation; only one of the two messages will appear (see Figure 3-3). If the number read more..

  • Page - 102

    84 javascript & jquery: the missing manual Making Programs React Intelligently JavaScript lets you perform the same kind of cascading logic using else if statements. It works like this: You start with an if statement, which is option number 1; you then add one or more else if statements to provide additional questions that can trigger additional options; read more..

  • Page - 103

    85 chapter 3: adding logic and control to your programs Making Programs React Intelligently Figure 3-4: With a basic conditional state- ment, the code inside the braces only runs if the condition is true. If the condition is false, that code is skipped and the program continues fridayCash >= 50 no yes alert('You should go out to a dinner and a movie.'); program continues read more..

  • Page - 104

    86 javascript & jquery: the missing manual Making Programs React Intelligently More Complex Conditions When you’re dealing with many different variables, you’ll often need even more complex conditional statements. For example, when validating a required email ad- dress field in a form, you’ll want to make sure both that the field isn’t empty and that the read more..

  • Page - 105

    87 chapter 3: adding logic and control to your programs Making Programs React Intelligently Note: To type a pipe character, press Shift-\. The key that types both backslashes and pipe characters is usually located just above the Return key. With the OR operator, only one condition needs to be true for the JavaScript that follows between the braces to run. As read more..

  • Page - 106

    88 javascript & jquery: the missing manual Making Programs React Intelligently if (! valid) { //print errors and don't submit form } The condition ! valid can be translated as “if not valid,” which means if valid is false, then the condition is true. To figure out the results of a condition that uses the NOT operator, just evaluate the condition without read more..

  • Page - 107

    89 chapter 3: adding logic and control to your programs Tutorial: Using Conditional Statements crucial pieces of a conditional statement, your script won’t work. There are a few things you can do as you type your JavaScript that can make it easier to work with conditional statements. • Type both of the curly braces before you type the code inside read more..

  • Page - 108

    90 javascript & jquery: the missing manual Tutorial: Using Conditional Statements 1. In a text editor, open the file conditional.html in the chapter03 folder. You’ll start by simply prompting the visitor for a number. This file already contains <script> tags in b oth the head and body regions. 2. Between the first set of <script> tags, in the page’s read more..

  • Page - 109

    91 chapter 3: adding logic and control to your programs Tutorial: Using Conditional Statements Note: Why two sets of script tags? When using the document.write() method to add content to a page, you have to place the document.write() code in the exact position on the page you want the message to appear—in this case, in the body below the <h1> tag. The first set read more..

  • Page - 110

    92 javascript & jquery: the missing manual Tutorial: Using Conditional Statements Preview the page in a web browser, and type 13 when the prompt dialog box appears. Press the browser’s reload button, and try different numbers as well as letters or other characters. You’ll notice that if you type a word or other non- number character, the final else read more..

  • Page - 111

    93 chapter 3: adding logic and control to your programs Handling Repetitive Tasks with Loops Handling Repetitive Tasks with Loops Sometimes a script needs to repeat the same series of steps over and over again. For example, say you have a web form with 30 text fields. When the user submits the form, you want to make sure that none of the fields read more..

  • Page - 112

    94 javascript & jquery: the missing manual Handling Repetitive Tasks with Loops Say you want to print the numbers 1 to 5 on a page. One possible way to do that is like this: document.write('Number 1 <br>'); document.write('Number 2 <br>'); document.write('Number 3 <br>'); document.write('Number 4 <br>'); document.write('Number 5 <br>'); Notice that each read more..

  • Page - 113

    95 chapter 3: adding logic and control to your programs Handling Repetitive Tasks with Loops The first time through this loop, the test would ask: Is 1 less than or equal to 5? The answer is yes, so document.write() runs. At the end of the loop (the last brace), the JavaScript interpreter goes back to the beginning of the loop and tests the read more..

  • Page - 114

    96 javascript & jquery: the missing manual Handling Repetitive Tasks with Loops first item in the days array above (Monday) is retrieved with days[0]. The second item is days[1], and so on. Here’s how you can use a while loop to print each item in this array: var counter = 0; while (counter < days.length) { document.write(days[counter] + ', '); counter++; read more..

  • Page - 115

    97 chapter 3: adding logic and control to your programs Handling Repetitive Tasks with Loops For Loops JavaScript offers another type of loop, called a for loop, that’s a little more compact (and a little more confusing). For loops are usually used for repeating a series of steps a certain number of times, so they often involve some kind of counter read more..

  • Page - 116

    98 javascript & jquery: the missing manual Handling Repetitive Tasks with Loops var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; for (var i=0; i<days.length; i++) { document.write(days[i] + ', '); } Tip: Seasoned programmers often use a very short name for counter variables in for loops. In the code above, the letter i read more..

  • Page - 117

    99 chapter 3: adding logic and control to your programs Handling Repetitive Tasks with Loops However, with a do/while loop, you can continually prompt the visitor for a number until she types one in. To see how this works, you’ll edit the page you completed on page 92: 1. In a text editor, open the conditional.html page you completed on page 92. (If read more..

  • Page - 118

    100 javascript & jquery: the missing manual Functions: Turn Useful Code Into Reusable Commands Functions: Turn Useful Code Into Reusable Commands Imagine that at work you’ve just gotten a new assistant to help you with your every task (time to file this book under “fantasy fiction”). Suppose you got hungry for a piece of pizza, but since the assistant was new read more..

  • Page - 119

    101 chapter 3: adding logic and control to your programs Functions: Turn Useful Code Into Reusable Commands brace, one or more lines of JavaScript and a final, closing curly brace. As with if statements, the curly braces mark the beginning and end of the JavaScript code that makes up the function. Note: As with if/else statements, functions are more read more..

  • Page - 120

    102 javascript & jquery: the missing manual Functions: Turn Useful Code Into Reusable Commands 2. Locate the code between the <script> tags in the <head> of the page, and type the following code: function printToday() { var today = new Date(); document.write(today.toDateString()); } The basic function is in place, but it doesn’t do anything yet. 3. Save the file read more..

  • Page - 121

    103 chapter 3: adding logic and control to your programs Functions: Turn Useful Code Into Reusable Commands function print(message) { document.write(message); } The name of this function is print and it has one parameter, named message. When this function is called, it receives some information (the message to be printed) and then it uses the document.write() read more..

  • Page - 122

    104 javascript & jquery: the missing manual Functions: Turn Useful Code Into Reusable Commands In this example, when functionName is called, argument1 is stored in parameter1, argument2 in parameter2, and so on. Expanding on the print function from above, suppose in addition to printing a message to the web page, you want to specify an HTML tag read more..

  • Page - 123

    105 chapter 3: adding logic and control to your programs Functions: Turn Useful Code Into Reusable Commands var formattedTotal = total.toFixed(2); return formattedTotal; } The first line stores the tax rate into a variable named TAX (which lets you easily change the rate simply by updating this line of code). The next three lines define the function. Don’t read more..

  • Page - 124

    106 javascript & jquery: the missing manual Functions: Turn Useful Code Into Reusable Commands One potential problem arises when you just plop a function down into an already- created script. What happens if the script uses the same variable names as the func- tion? Will the function overwrite the variable from the script, or vice versa? For example: var message = read more..

  • Page - 125

    107 chapter 3: adding logic and control to your programs Functions: Turn Useful Code Into Reusable Commands var message = 'Outside the function'; function warning() { var message ='Inside the function'; alert( message ); } warning(); // 'Inside the function' alert( message ); //'Outside the function' Here, the code creates a message variable twice—in the first line of the read more..

  • Page - 126

    108 javascript & jquery: the missing manual Tutorial: A Simple Quiz Figure 3-9: There’s a subtle yet crucial dif- ference when assigning values to variables within a function. If you want the variable to only be accessible to the code inside the function, make sure to use the var keyword to create the vari- able inside the function (top). If you don’t use var, read more..

  • Page - 127

    109 chapter 3: adding logic and control to your programs Tutorial: A Simple Quiz the prompt() command. In addition, you’ll need a list of questions; since arrays are good for storing lists of information, you’ll use an array to store your quiz questions. • Let quiz-taker know if she’s right or wrong. First, you need to determine if the read more..

  • Page - 128

    110 javascript & jquery: the missing manual Tutorial: A Simple Quiz array statement. You’ll be typing the array over multiple lines as described on page 61. 4. Press Return twice to add two new lines and type ];. Your code should now look like this: var score = 0; var questions = [ ]; Since the quiz is made up of a bunch of questions, it makes read more..

  • Page - 129

    111 chapter 3: adding logic and control to your programs Tutorial: A Simple Quiz Now that the basic variables for the quiz are set up, it’s time to figure out how to ask each question. The questions are stored in an array, and you want to ask each question in the list. As you’ll recall from page 95, a loop is a perfect way to go read more..

  • Page - 130

    112 javascript & jquery: the missing manual Tutorial: A Simple Quiz change those easily; functions appear next, since they usually form the core of most scripts; and finally, the step-by-step actions (like the loop) appear last. 11. Add the following code: function askQuestion(question) { } This code indicates the body of the function—it’s al ways a good idea to read more..

  • Page - 131

    113 chapter 3: adding logic and control to your programs Tutorial: A Simple Quiz This code is just a basic if/else statement. The condition—answer == question[1]— checks to see if what the user entered (answer) is the same as the answer, which is stored as the second item in the array (question[1]). If they match, then the quiz-taker was right: An alert read more..

  • Page - 132

    114 javascript & jquery: the missing manual Tutorial: A Simple Quiz Figure 3-10: The results of your simple quiz program. After you learn more about how to ma- nipulate a web page on page 138, respond to events on page 157, and work with web forms on page 257, try to rewrite this quiz program so the questions appear di- rectly within the web page, and the score read more..

  • Page - 133

    2 Part Two: Getting Started with jQuery Chapter 4: Introducing jQuery Chapter 5: Action/Reaction: Making Pages Come Alive with Events Chapter 6: Animations and Effects read more..

  • Page - 134

    read more..

  • Page - 135

    117 chapter 4 Introducing jQuery The first chapters of this book covered many of the fundamentals of the Java Script programming language—the keywords, concepts, and syntax of JavaScript. Many of these concepts were fairly straightforward (“a variable is like a box in which you put a value”), but some topics may have had you scratch- ing your head read more..

  • Page - 136

    118 javascript & jquery: the missing manual About JavaScript Libraries Fortunately, JavaScript libraries offer a way to leap-frog past many time-consuming programming details. A JavaScript library is a collection of JavaScript code that provides simple solutions to many of the mundane, day-to-day details of JavaScript. Think of it as a collec- tion of read more..

  • Page - 137

    119 chapter 4: introducing jquery Getting jQuery UP TO SPEED Other Libraries jQuery isn’t the only JavaScript library in town. There are many, many others. Some are designed to perform specific tasks, and others are all-purpose libraries aimed at solving every JavaScript task under the sun. Here are a few of the most popular: • Yahoo User Interface Library (http://developer read more..

  • Page - 138

    120 javascript & jquery: the missing manual Getting jQuery There are a couple of downsides to using a CDN: First, visitors need to be connected to the Internet for this method to work. That becomes an issue if you need to make sure your site works offline, for example, in a kiosk at a museum or during a pro- gramming demonstration in a read more..

  • Page - 139

    121 chapter 4: introducing jquery Getting jQuery 2. Click the “Current Release” link near the top of the page, or scroll down until you see the Current Release headline. The jQuery file comes in two versions on the download site—minified and uncompressed. The uncompressed file is very large (over 200 k), and is only provided so you can learn more read more..

  • Page - 140

    122 javascript & jquery: the missing manual Adding jQuery to a Page FREQUENTLY ASKED QUESTION jQuery Versions I see that this book uses version 1.6.3 of jQuery, but the current version on the jQuery site is 1.X. Is this a problem? jQuery is always evolving. New bugs are often discovered, and the jQuery team works diligently to fix them. In addi- tion, as new web read more..

  • Page - 141

    123 chapter 4: introducing jquery Adding jQuery to a Page Tip: When using the Google CDN, you can leave off parts of the version number. If you use 1.6 instead of 1.6.1 in the link (<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js”></script>), then Google loads the latest version in the 1.6 family—1.6.3, for example. If jQuery is updated to 1.6.9, read more..

  • Page - 142

    124 javascript & jquery: the missing manual Modifying Web Pages: An Overview In addition, here are a few things to keep in mind: • The link to the jQuery file must precede any programming that relies on jQuery. In other words, don’t put any other script tags before the <script> tag that loads jQuery. • Put your JavaScript programming after any read more..

  • Page - 143

    125 chapter 4: introducing jquery Modifying Web Pages: An Overview Figure 4-1: JavaScript can make web pages simpler to scan and read by only showing content when it’s needed. At Netflix.com, movie descriptions are hidden from view, but revealed when the mouse travels over the movie title or thumbnail image. It may seem hard to believe, but, if you know how to read more..

  • Page - 144

    126 javascript & jquery: the missing manual Modifying Web Pages: An Overview If you look under the hood of the calendar, you’ll find a series of HTML tags such as divs, a table, and <td> tags, with special classes and IDs (ui-datepicker-month, ui-datepicker-div, and so on) applied to them. A style sheet with class and ID styles adds color, read more..

  • Page - 145

    127 chapter 4: introducing jquery Understanding the Document Object Model • Remove the element. In the Netflix example pictured in Figure 4-1, the pop-up bubble disappears when you mouse off the movie title. In this case, JavaScript removes that pop-up bubble from the page. • Extract information from the element. Other times, you’ll want to know something read more..

  • Page - 146

    128 javascript & jquery: the missing manual Understanding the Document Object Model To see how the DOM works, take look at this very simple web page: <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>A web page</title> </head> <body class="home"> <h1 id="header">A headline</h1> <p>Some <strong>important</strong> read more..

  • Page - 147

    129 chapter 4: introducing jquery Selecting Page Elements: The jQuery Way WORKAROUND WORKSHOP The Problem with the DOM Unfortunately, the major browsers have tranditionally in- terpreted the DOM differently. For example, versions of Internet Explorer prior to 9 handle events differently from other browsers; the same HTML can produce more text nodes in Firefox and Safari than in read more..

  • Page - 148

    130 javascript & jquery: the missing manual Selecting Page Elements: The jQuery Way $('#banner') The #banner is the CSS selector used to style a tag with the ID name banner—the # part indicates that you’re identifying an ID. Of course, once you select one or more elements, you’ll want to do something with them—jQuery provides many tools for read more..

  • Page - 149

    131 chapter 4: introducing jquery Selecting Page Elements: The jQuery Way Figure 4-4: The file selectors.html, provided with this book’s tutorial files, lets you try out jQuery selec- tors. Type a selector in the Selector form field (circled), and then click Apply. The page converts your selector into a jQuery object, and any ele- ments that match the selector you typed turn read more..

  • Page - 150

    132 javascript & jquery: the missing manual Selecting Page Elements: The jQuery Way program each of the main navigation buttons to open a drop-down menu when someone mouses over the button. Note: Because finding all elements with a particular class name is such a common task, the latest version of most browsers support a method to do that. But since not all read more..

  • Page - 151

    133 chapter 4: introducing jquery Selecting Page Elements: The jQuery Way Advanced Selectors jQuery also lets you use more complicated CSS selectors to accurately pinpoint the tags you wish to select. Don’t worry too much about mastering these right now: Once you’ve read a few more chapters and gained a better understanding of how jQuery works and how to read more..

  • Page - 152

    134 javascript & jquery: the missing manual Selecting Page Elements: The jQuery Way $('img[alt]') There are a handful of different attribute selectors: • [attribute] selects elements that have the specified attribute assigned in the HTML. For example, $(a[href]) locates all <a> tags t hat have an href attribute set. Selecting by attribute lets you exclude named read more..

  • Page - 153

    135 chapter 4: introducing jquery Selecting Page Elements: The jQuery Way jQuery Filters jQuery also provides a way to filter your selections based on certain characteristics. For example, the :even filter lets you select every even element in a collection of elements. In addition, you can find elements that contain particular tags, specific text, elements that are read more..

  • Page - 154

    136 javascript & jquery: the missing manual Selecting Page Elements: The jQuery Way This setup is different from a descendent selector, since it doesn’t select the <a>; it selects <li> tags, but only those <li> tags with a link inside them. • :contains() finds elements that contain specific text. For example, to find every link that says “Click read more..

  • Page - 155

    137 chapter 4: introducing jquery Selecting Page Elements: The jQuery Way Because looping through a collection of elements is so common, jQuery functions have that feature built right in. In other words, when you apply a jQuery function to a selection of elements, you don’t need to create a loop yourself, since the function does it automatically. For read more..

  • Page - 156

    138 javascript & jquery: the missing manual Adding Content to a Page The ability to chain functions is pretty unusual and is a specific feature of jQuery— in other words, you can’t add non-jQuery functions (either ones you create or built- in JavaScript functions) in the chain. Adding Content to a Page jQuery provides many functions for manipulating elements and read more..

  • Page - 157

    139 chapter 4: introducing jquery Adding Content to a Page • .text() works like .html() but it doesn’t accept HTML tags. It’s useful when you want to replace the text within a tag. For example, in the code at the beginning of this section, you’ll see an <h2> tag with the text “Errors:” in i t. Say, after run- ning a program to check read more..

  • Page - 158

    140 javascript & jquery: the missing manual Adding Content to a Page <input type="text" name="userName" id="userName"> Now suppose that when the visitor submits the form, this field is empty. You can write a program that checks the field and then adds an error message after the field. To add the message after this field (don’t worry right now read more..

  • Page - 159

    141 chapter 4: introducing jquery Setting and Reading Tag Attributes Note: jQuery also includes a function named clone() that lets you make a copy of a selected element. You’ll see this function in action in the tutorial on page 150. HELPFUL TOOL ALERT Skip View Source One problem with using JavaScript to manipulate the DOM by adding, changing, deleting, and rearranging read more..

  • Page - 160

    142 javascript & jquery: the missing manual Setting and Reading Tag Attributes Classes Cascading Style Sheets are a very powerful technology, letting you add all sorts of sophisticated visual formatting to your HTML. One CSS rule can add a colorful background to a page, while another rule might completely hide an element from view. You can create some really read more..

  • Page - 161

    143 chapter 4: introducing jquery Setting and Reading Tag Attributes • Finally, you may want to toggle a particular class—meaning add the class if it doesn’t already exist, or remove the class if it does. Toggling is a popular way to show an element in either an on or off state. For example, when you click a radio button, it’s checked read more..

  • Page - 162

    144 javascript & jquery: the missing manual Setting and Reading Tag Attributes The css() function also lets you set a CSS property for an element. To use the func- tion this way, you supply two arguments to the function: the CSS property name and a value. For example, to change the font size for the <body> tag to 200% size, you can do this: read more..

  • Page - 163

    145 chapter 4: introducing jquery Setting and Reading Tag Attributes highlight a <div> tag (perhaps in reaction to an action taken by a visitor), you can change the <div> tag’ s background color and add a border around it, like this: $('#highlightedDiv').css('background-color','#FF0000'); $('#highlightedDiv').css('border','2px solid #FE0037'); Another way is to pass read more..

  • Page - 164

    146 javascript & jquery: the missing manual Reading, Setting, and Removing HTML Attributes Study this example closely, because it looks a little different from what you’ve seen so far, and because you’ll be encountering lots of code that looks like it in future chap- ters. The first thing to notice is that this code is merely a single JavaScript read more..

  • Page - 165

    147 chapter 4: introducing jquery Acting on Each Element in a Selection The attr() function returns the attributes value as it’s set in the HTML. This code returns the src property for the first <img> tag inside another tag with an ID of banner, so the variable imageFile would contain the path set in the page’s HTML: for instance, read more..

  • Page - 166

    148 javascript & jquery: the missing manual Acting on Each Element in a Selection Anonymous Functions To use the each() function, you pass a special kind of argument to it—an anonymous function. The anonymous function is simply a function containing the steps that you wish to perform on each selected element. It’s called anonymous because, unlike the read more..

  • Page - 167

    149 chapter 4: introducing jquery Acting on Each Element in a Selection Fifty alert dialog boxes with the message “I found an image” would appear. (That’d be really annoying, so don’t try this at home.) Note: This may look somewhat familiar. As you saw on page 123, when you add jQuery to a page, you should use the document.ready() function to make read more..

  • Page - 168

    150 javascript & jquery: the missing manual Automatic Pull Quotes The first step is to get a list of all links pointing outside your site. You can do so using an attribute selector (page 133): $('a[href^="http://"]') Now to loop through each link, we add the each() function: $('a[href^="http://"]').each() Then add an anonymous function: read more..

  • Page - 169

    151 chapter 4: introducing jquery Automatic Pull Quotes Creating all that HTML takes time and adds extra HTML and duplicate text to the finished page. Fortunately, with JavaScript, you can quickly add any number of pull quotes to a page, adding just a small amount of HTML. Figure 4-7: Adding pull quotes manually to the HTML of a page is a pain, especially read more..

  • Page - 170

    152 javascript & jquery: the missing manual Automatic Pull Quotes 2. Duplicate each <span> tag. Each pull quote box is essentially another span tag with the same text inside it, so you can use JavaScript to just duplicate the current <span> tag. 3. Remove the pq class from the duplicate <span> and add a new class pullquote. The formatting magic—the read more..

  • Page - 171

    153 chapter 4: introducing jquery Automatic Pull Quotes 4. Click on the empty line between the <script> tags a nd add the code in bold: 1 <script src="../_js/jquery-1.6.3.min.js"><script> 2 <script> 3 $(document).ready(function() { 4 5 }); // end ready 6 </script> The JavaScript comment // end ready is particularly helpful as read more..

  • Page - 172

    154 javascript & jquery: the missing manual Automatic Pull Quotes 6 }); // end each 7 }); // end ready 8 </script> This function starts by creating a new variable named quote, which contains a “clone” (j ust a copy) of the current <span> (see page 149 if you forgot what $(this) means). The jQuery .clone() function duplicates the read more..

  • Page - 173

    155 chapter 4: introducing jquery Automatic Pull Quotes Although the text looks like it will appear duplicated side by side, the CSS formatting makes the pull quote box float to the right edge of the page. Note: To achieve the visual effect of a pull quote box, the page has a CSS style that uses the CSS float property. The box is moved to the read more..

  • Page - 174

    read more..

  • Page - 175

    157 chapter 5 Action/Reaction: Making Pages Come Alive with Events When you hear people talk about JavaScript, you usually hear the word “interactive” so mewhere in the conversation: “JavaScript lets you make interactive web pages.” What they’re really saying is that JavaScript lets your web pages react to something a visitor does: moving a mouse over a read more..

  • Page - 176

    158 javascript & jquery: the missing manual What Are Events? An event represents the precise moment when something happens. For example, when you click a mouse, the precise moment you release the mouse button, the web browser signals that a click event has just occurred. The moment that the web browser indicates that an event has happened is when the event read more..

  • Page - 177

    159 chapter 5: action/reaction: making pages come alive with events What Are Events? Mouse Events Ever since Steve Jobs introduced the Macintosh in 1984, the mouse has been a criti- cal device for all personal computers. Folks use it to open applications, drag files into folders, select items from menus, and even to draw. Naturally, web browsers provide lots of read more..

  • Page - 178

    160 javascript & jquery: the missing manual What Are Events? Note: Some web browsers, like Internet Explorer, support many events (http://msdn2.microsoft.com/ en-us/library/ms533051(VS.85).aspx), but most browsers share just a handful of events. Document/Window Events The browser window itself understands a handful of events that fire from when the page loads to when the visitor read more..

  • Page - 179

    161 chapter 5: action/reaction: making pages come alive with events What Are Events? Form Events In the pre-JavaScript days, people interacted with websites mainly via forms created with HTML. Entering information into a form field was really the only way for visi- tors to provide input to a website. Because forms are still such an important part of read more..

  • Page - 180

    162 javascript & jquery: the missing manual Using Events the jQuery Way Keyboard Events Web browsers also track when visitors use their keyboards, so you can assign com- mands to keys or let your visitors control a script by pressing various keys. For example, pressing the space bar could start and stop a JavaScript animation. Unfortunately, the different read more..

  • Page - 181

    163 chapter 5: action/reaction: making pages come alive with events Using Events the jQuery Way 2. Assign an event. In jQuery, most DOM events have an equivalent jQuery function. So to assign an event to an element, you just add a period, the event name, and a set of pa- rentheses. So, for example, if you want to add a mouseover event to every read more..

  • Page - 182

    164 javascript & jquery: the missing manual Using Events the jQuery Way Figure 5-2: In jQuery, an event works like a function, so you can pass an argument to the event. You can think of an anonymous function, then, as an argument—like a single piece of data that’s passed to a function. If you think of it that way, it’s easier to see how all of the little read more..

  • Page - 183

    165 chapter 5: action/reaction: making pages come alive with events Tutorial: Introducing Events Tutorial: Introducing Events This tutorial gives you a quick introduction to using events. You’ll make the page react to several different types of events so you can get a handle on how jQuery events work and how to use them. Note: See the note on page 29 for read more..

  • Page - 184

    166 javascript & jquery: the missing manual Tutorial: Introducing Events The $(‘html’) selects the HTML element; basically, the entire browser window. Next, you’ll add an event. 6. Type .dblclick(); after the jQuery selector so your code looks like this: <script src="../_js/jquery-1.6.3.min.js"></script> <script> $(document).ready(function() { read more..

  • Page - 185

    167 chapter 5: action/reaction: making pages come alive with events Tutorial: Introducing Events Now that you’ve got the basics, you’ll try out a few other events. 9. Add the code in bold below so your script looks like this: <script src="../_js/jquery-1.6.3.min.js"></script> <script> $(document).ready(function() { $('html').dblclick(function() { read more..

  • Page - 186

    168 javascript & jquery: the missing manual Tutorial: Introducing Events alert('ouch'); }); // end double click $('a').mouseover(function() { var message = "<p>You moused over a link</p>"; $('.main').append(message); }); // end mouseover $('#button').click(function() { $(this).val("Stop that!"); }); // end click }); // end read more..

  • Page - 187

    169 chapter 5: action/reaction: making pages come alive with events More jQuery Event Concepts Figure 5-3: jQuery makes it easy for your web pages to respond to user interaction, such as opening an alert box when the page is clicked twice, adding text to the page in response to mousing over a link, or clicking a form button. More jQuery Event Concepts Because events are read more..

  • Page - 188

    170 javascript & jquery: the missing manual More jQuery Event Concepts The most common way to deal with that problem has been to use the load event to wait until a page is fully downloaded and displayed before executing any JavaScript. Unfortunately, waiting until a page fully loads before running JavaScript code can create some pretty strange results. The read more..

  • Page - 189

    171 chapter 5: action/reaction: making pages come alive with events More jQuery Event Concepts Tip: Because the ready() function is used nearly anytime you add jQuery to a page, there’s a shorthand way of writing it. You can remove the $(document).ready part, and just type this: $(function() { // do something on document ready }); jQuery Events jQuery also provides read more..

  • Page - 190

    172 javascript & jquery: the missing manual More jQuery Event Concepts To make a statement containing multiple anonymous functions easier to read, move each function to its own line. So a slightly more readable version of the code above would look like this: $('#menu').hover( function() { $('#submenu').show(); }, // end mouseover function() { read more..

  • Page - 191

    173 chapter 5: action/reaction: making pages come alive with events More jQuery Event Concepts The toggle() Event jQuery’s toggle() event works identically to the hover() event, except that instead of responding to mouseover and mouseout events, it responds to clicks. One click triggers the first function; the next click triggers the second function. Use this event read more..

  • Page - 192

    174 javascript & jquery: the missing manual More jQuery Event Concepts In jQuery, the event object is available to the function assigned to handling the event. In fact, the object is passed as an argument to the function, so to access it, you just include a parameter name with the function. For example, say you want to find the X and Y position read more..

  • Page - 193

    175 chapter 5: action/reaction: making pages come alive with events More jQuery Event Concepts Tip: If you access the event object’s which property with the keypress() event, you’ll get a numeric code for the key pressed. If you want the specific key that was pressed (a, K, 9, and so on), you need to run the which property through a JavaScript method that read more..

  • Page - 194

    176 javascript & jquery: the missing manual More jQuery Event Concepts 1 $('a').mouseover(function() { 2 alert('You moved the mouse over me!'); 3 }); 4 $('#disable').click(function() { 5 $('a').unbind('mouseover'); 6 }); Lines 1–3 add a function to the mouseover event for all links (<a> tags) on the page. Moving the mouse over the link read more..

  • Page - 195

    177 chapter 5: action/reaction: making pages come alive with events Advanced Event Management Advanced Event Management You can live a long, happy programming life using just the jQuery event methods and concepts discussed on the previous pages. But if you really want to get the most out of jQuery’s event-handling techniques, then you’ll want to learn about the read more..

  • Page - 196

    178 javascript & jquery: the missing manual Advanced Event Management Suppose you wanted to pop up an alert box in response to an event, but you wanted the message in the alert box to be different based on which element triggered the event. One way to do that would be to create variables with different object literals inside, and then send the read more..

  • Page - 197

    179 chapter 5: action/reaction: making pages come alive with events Advanced Event Management Other Ways to Use the bind() Function jQuery’s bind() function gives you a lot of programming flexibility. In addition to the techniques listed in the previous section, it also lets you tie two or more events to the same function. For example, say you write a read more..

  • Page - 198

    180 javascript & jquery: the missing manual Tutorial: A One- Page FAQ Tutorial: A One-Page FAQ “Frequently Asked Questions” pages are a common sight on the web. They can help improve customer service by providing immediate answers 24/7. Unfortunately, most FAQ pages are either one very long page full of questions and complete an- swers, or a single page read more..

  • Page - 199

    181 chapter 5: action/reaction: making pages come alive with events Tutorial: A One- Page FAQ function is discussed on page 187). Save the page and open it in a web browser. The answers should all be hidden. The next step is determining which elements you need to add an event listener to. Since the answer appears when a visitor clicks the question, you read more..

  • Page - 200

    182 javascript & jquery: the missing manual Tutorial: A One- Page FAQ 12 ); // end of toggle() 13 }); // end of ready() 14 </script> Be sure you don’t leave out the comma at the end of line 8 above. Remember that the two functions here act like arguments passed to a function (page 102). When you call a function, you separate read more..

  • Page - 201

    183 chapter 5: action/reaction: making pages come alive with events Tutorial: A One- Page FAQ 9 function() { 10 $(this).next('.answer').fadeOut(); 11 } 12 ); // end of toggle() 13 }); // end of ready() 14 </script> Now the answer fades out on a second click. Save the page and give it a try. read more..

  • Page - 202

    184 javascript & jquery: the missing manual Tutorial: A One- Page FAQ Figure 5-6: With just a few lines of JavaScript, you can make page elements appear or disappear with a click of the mouse. read more..

  • Page - 203

    185 chapter 6 Animations and Effects In the last two chapters, you learned the basics of using jQuery: how to load the jQuery library, select page elements, and respond to events like a visitor click- ing on a button or mousing over a link. Most jQuery programs involve three steps: selecting an element on the page, attaching an event to that read more..

  • Page - 204

    186 javascript & jquery: the missing manual jQuery Effects (1,000 is 1 second, 500 is half of a second, and so on). For example, the code to make an element fade out of view slowly would look like this: $('element').fadeOut('slow'); Or if you want the element to fade out really slowly, over the course of 10 seconds: $('element').fadeOut(10000); When you read more..

  • Page - 205

    187 chapter 6: animations and effects jQuery Effects Basic Showing and Hiding jQuery provides three functions for basic hiding and showing of elements: • show() makes a hidden element visible. It doesn’t have any effect if the element is already visible on the page. If you don’t supply a speed value, the element appears immediately. However, if you read more..

  • Page - 206

    188 javascript & jquery: the missing manual jQuery Effects $('#button').click(function() { $('#instructions').fadeToggle(500); }); // end click • fadeTo() works slightly differently than other effect functions. It fades an image to a specific opacity. For example, you can make an image fade so that it’s semi- transparent. Unlike other effects, you must read more..

  • Page - 207

    189 chapter 6: animations and effects jQuery Effects UP TO SPEED Absolute Positioning with CSS Normally, when you hide an element on a web page, other elements move to fill the space. For example, if you hide an image on a page, the image disappears, and content below that image moves up the page. Likewise, making an ele- ment appear forces other content to move to read more..

  • Page - 208

    190 javascript & jquery: the missing manual Tutorial: Login Slider Tutorial: Login Slider In this tutorial, you’ll get a little practice with using jQuery effects by creating a com- mon user interface element: a panel that slides into and out of view with a click of the mouse (see Figure 6-2). Figure 6-2: Now you don’t see it, now you do. The login read more..

  • Page - 209

    191 chapter 6: animations and effects Tutorial: Login Slider The Programming 1. In a text editor, open the file signup.html in the chapter06 folder. This file already contains a link to the jQuery file, and the $(document).ready() function (page 169) is in place. First, you’ll select the paragraph with the “Login” text. 2. Click in the empty line after the read more..

  • Page - 210

    192 javascript & jquery: the missing manual Animations 6. Save the page and preview it in a web browser. Make sure you click the “Login” pa ragraph several times to see how it works. You’ll find a finished version of the tutorial—complete_signup.html—in th e chapter06 folder. Try out the other toggle effects as well, by replacing slideToggle() with toggle() read more..

  • Page - 211

    193 chapter 6: animations and effects Animations edge of the page, changing its opacity to 50%, and enlarging its font size to 24 pixels. The following code creates an object with those properties and values: { left: '650px', opacity: .5, fontSize: '24px' } Note that you only have to put the value in quotes if it includes a measurement like read more..

  • Page - 212

    194 javascript & jquery: the missing manual Animations You can also set a property relative to its current value using += or -= as part of the animation options. For example, say you want to animate an element by moving it 50 pixels to the right each time you click on it. Here’s how: $('#moveIt').click(function() { $(this).animate( { read more..

  • Page - 213

    195 chapter 6: animations and effects Animations When using the animate() function, the easing method is the third argument after the object literal containing the CSS properties you wish to animate, and the overall speed of the animation. For example, to use the linear easing method with the ani- mation code from page 193, you’d write: $('#message').animate( { read more..

  • Page - 214

    196 javascript & jquery: the missing manual Performing an Action After an Effect Is Completed Lines 1 and 2 load jQuery and the easing plug-in. Line 4 is the every-present ready() function (page 169), and line 5 adds a click handler to the div. The heart of the action are lines 6–12. As you’ll recall from page 149, when you’re inside of an read more..

  • Page - 215

    197 chapter 6: animations and effects Performing an Action After an Effect Is Completed its width and height from zero to full size (a kind of zooming effect). You can use the animate() function to do that, and then display the caption like this: 1 $('#photo').width(0).height(0).css('opacity',0); 2 $('#caption').hide(); 3 $('#photo').animate( 4 { 5 width: read more..

  • Page - 216

    198 javascript & jquery: the missing manual Tutorial: Animated Dashboard However, you don’t need to use a callback function if you want to add additional animations to the same page element. For example, say you want to move a photo onto the screen, then make it fade out of view. In this case, you simply use the animate() function to read more..

  • Page - 217

    199 chapter 6: animations and effects Tutorial: Animated Dashboard Figure 6-3: You can have a lot of fun by hiding page elements off one of the edges of the browser window (like the div in the left image, which is mostly out of view). Using the animate() function, you can then bring that page element fully into view (right). Note: See the note on page 29 read more..

  • Page - 218

    200 javascript & jquery: the missing manual Tutorial: Animated Dashboard The hover event (described on page 171) is a special jQuery function, not a real JavaScript event, that lets you perform one set of actions when a visitor mouses over an element, then a second set of actions when the visitor mouses off the element (the hover event is really just a read more..

  • Page - 219

    201 chapter 6: animations and effects Tutorial: Animated Dashboard $(document).ready(function() { $('#dashboard').hover( function() { }, function() { } ); // end hover }); // end ready jQuery plug-ins (which you’ll learn more about in the next chapter) are simply external JavaScript files that add functionality to jQuery, and read more..

  • Page - 220

    202 javascript & jquery: the missing manual Tutorial: Animated Dashboard 7. Type a comma after the closing } of the object literal, press Returns and then type 500. The comma marks the end of the first argument passed to the animate() func- tion, while the 500 sets the length of the animation to half a second or 500 mil- liseconds. Lastly, you’ll set read more..

  • Page - 221

    203 chapter 6: animations and effects Tutorial: Animated Dashboard You’ll see the div move into view and then out of view. However, if you move the mouse over and off the div repeatedly and quickly, you’ll notice some strange behavior: The div will keep sliding in and out of view long after you’ve finished moving the mouse. This problem is caused read more..

  • Page - 222

    read more..

  • Page - 223

    3 Part Three: Building Web Page Features Chapter 7: Improving Your Images Chapter 8: Improving Navigation Chapter 9: Enhancing Web Forms Chapter 10: Expanding Your Interface read more..

  • Page - 224

    read more..

  • Page - 225

    207 chapter 7 Improving Your Images Web designers use images to improve a page’s design, decorate navigation bars, highlight elements on a page—and to show the world what fun they had on their last vacation. Adding an image to a web page immediately injects interest and visual appeal. When you add JavaScript to the mix, however, you can really read more..

  • Page - 226

    208 javascript & jquery: the missing manual Swapping Images Changing an Image’s src Attribute Every image displayed on a web page has a src (short for source) attribute that indi- cates a path to a graphic file; in other words, it points to an image on a web server. If you change this property to point to a different graphic file, the browser read more..

  • Page - 227

    209 chapter 7: improving your images Swapping Images The key to this technique is line 1, which creates a new image object. To a web browser, the code new Image()says, “Browser, I’m going to be adding a new image to the page, so get ready.” The next line tells the web browser to actually download the new image. Line 3 gets a reference to the read more..

  • Page - 228

    210 javascript & jquery: the missing manual Swapping Images What makes this preloading is that you do it before you need to replace an image currently on the web page. One way to preload is to create an array (page 59) at the beginning of a script containing the paths to all graphics you wish to preload, then loop through that list, read more..

  • Page - 229

    211 chapter 7: improving your images Tutorial: Adding Rollover Images 1 <script src="js/jquery-1.6.3.min.js"></script> 2 <script> 3 $(document).ready(function() { 4 var newPhoto = new Image(); 5 newPhoto.src = 'images/newImage.jpg'; 6 var oldSrc=$('#photo').attr('src'); 7 $('#photo').hover( 8 function() { 9 read more..

  • Page - 230

    212 javascript & jquery: the missing manual Tutorial: Adding Rollover Images Figure 7-1: Make a navigation bar, link, or simply a photo more visu- ally interactive with rollovers. Overview of the Task The tutorial file rollover.html (located in the chapter07 tutorial folder) contains a series of six images (see Figure 7-2). Each image is wrapped by a link that points read more..

  • Page - 231

    213 chapter 7: improving your images Tutorial: Adding Rollover Images Figure 7-2: The basic structure of the HTML for this tutorial includes a <div> tag that surrounds a series of links with images in them. To make swapping in the new image easy, its file name is simply a version of the original image’s file name. From this description, you can see that both read more..

  • Page - 232

    214 javascript & jquery: the missing manual Tutorial: Adding Rollover Images 3. Press Return twice, and then type }); // end each to close the anonymous func- tion, end the call to the each() function, and terminate the JavaScript state- ment. Your code should now look like this: 1 <script src="../_js/jquery-1.6.3.min.js"></script> 2 <script> read more..

  • Page - 233

    215 chapter 7: improving your images Tutorial: Adding Rollover Images Here’s the creative part: Instead of manually typing the src of the rollover to preload it like this, preloadImage.src=‘_images/small/blue_h.jpg’, yo u can let JavaScript figure out the src by simply changing the name of the original im- age’s source so it reflects the name of the read more..

  • Page - 234

    216 javascript & jquery: the missing manual Tutorial: Photo Gallery with Effects function() { $(this).attr('src', preloadImage.src); }, This first function simply changes the src property of the current image to the src of the rollover image. The comma at the end of the last line is required be- cause the function you just added is acting as the first read more..

  • Page - 235

    217 chapter 7: improving your images Tutorial: Photo Gallery with Effects Figure 7-3: The finished photo gallery page. Clicking a thumbnail makes a larger image fade into view and the current image fade out. The completed version of this tutorial file, complete_ gallery.html, is in the chapter07 folder. Overview of Task The way the gallery works is pretty straightforward—click read more..

  • Page - 236

    218 javascript & jquery: the missing manual Tutorial: Photo Gallery with Effects Figure 7-4: The basic structure of the photo gallery. All of the thumbnail images are wrapped in links that point to the larger version of the photo. Clicking each link will load the larger image inside a <div> tag with the ID of photo. <div id="gallery"> <a read more..

  • Page - 237

    219 chapter 7: improving your images Tutorial: Photo Gallery with Effects 1. In a text editor, open the file gallery.html in the chapter07 folder. This file contains the programming from the previous tutorial, plus a new <div> tag to display the large version of each thumbnail image. Since the process of displaying a gallery image is triggered by read more..

  • Page - 238

    220 javascript & jquery: the missing manual Tutorial: Photo Gallery with Effects 5. Hit Return and type var oldImage = $(‘#photo img’);. The variable oldImage holds a jQuery selection containing the <img> tag inside the photo <div> (see Figure 7-4). Now it’s time to create a tag for the new image. 6. Hit Return again and add var newImage = $(‘<img read more..

  • Page - 239

    221 chapter 7: improving your images Tutorial: Photo Gallery with Effects Figure 7-5: To achieve the effect where two photos ap- pear in the same spot on the page, but one photo fades in and another fades out, you need to use some creative CSS. Absolute po- sitioning lets an element sit above the page, and even on top of another element. In this case, both images read more..

  • Page - 240

    222 javascript & jquery: the missing manual Advanced Gallery with jQuery FancyBox 9. Add one last line after the end of the click() function (line 13 below), so your completed code looks like this: 1 $('#gallery a').click(function(evt) { 2 evt.preventDefault(); 3 var imgPath = $(this).attr('href'); 4 var oldImage = $('#photo img'); 5 read more..

  • Page - 241

    223 chapter 7: improving your images Advanced Gallery with jQuery FancyBox Figure 7-6: The FancyBox jQuery plug-in, created by Janis Skarnelis, gives you an easy way to create an attractive, single-page photo gallery. You can even set up FancyBox so that visitors can navigate through a series of photos by clicking a Next or Previous button that appears when you mouse read more..

  • Page - 242

    224 javascript & jquery: the missing manual Advanced Gallery with jQuery FancyBox Tip: To add a caption to a photo, just supply a title attribute to the <a> tag that links to the large image. For example: <a href="images/potato.jpg" title="A handsome potato”> 2. Download the FancyBox files and put them into your site. You can find the files at read more..

  • Page - 243

    225 chapter 7: improving your images Advanced Gallery with jQuery FancyBox <script src="js/jquery-1.6.3.min.js"></script> <script src="fancybox/jquery.fancybox-1.3.4.js"></script> In addition, FancyBox can use the easing methods described on page 194 to control how the larger images zoom into or out of the page. If you wish to use any easing read more..

  • Page - 244

    226 javascript & jquery: the missing manual Advanced Gallery with jQuery FancyBox To create a gallery of related images, simply add the rel attribute to the <a> tag and assign the same value for each image in the gallery. For example: <a href="large_slide1.jpg" rel="gallery"> <img src="slide1.jpg" width="70" height="70"> read more..

  • Page - 245

    227 chapter 7: improving your images Advanced Gallery with jQuery FancyBox jQuery FancyBox accepts a lot of different options (visit http://fancybox.net/api/ for the complete list), but here are the most useful: • overlayColor. The background color that covers the page while FancyBox dis- plays an image. This option accepts a hex color value like #FF0033. If read more..

  • Page - 246

    228 javascript & jquery: the missing manual Advanced Gallery with jQuery FancyBox easingIn : 'easeInBounce', easingOut : 'easeOutSine' • titlePosition. Normally, when you add a caption to an image (see the Note on page 231), FancyBox places the caption inside a graphic box (a lozenge-shaped image). You can change this graphic (see page 229), or simply not use it read more..

  • Page - 247

    229 chapter 7: improving your images Advanced Gallery with jQuery FancyBox and shifts the image using the background-position property so that only the top- right corner of the fancybox.png file appears. The reasoning behind this approach is that by only loading a single file—fancybox.png—instead of separate files for each control, your website will download read more..

  • Page - 248

    230 javascript & jquery: the missing manual Advanced Gallery with jQuery FancyBox ways to modify this. If you’re not happy with the 30-pixel by 30-pixel size, you can simply edit the fancybox.png file: Delete the 30 30 image in the top-right of that file and replace it with a design of your own. In the FancyBox stylesheet (the read more..

  • Page - 249

    231 chapter 7: improving your images Tutorial: FancyBox Photo Gallery • Border color around pop-up images. Normally, FancyBox displays a white border around a pop-up image. As mentioned in the previous section, you can control the size of that border by sending a padding value to the FancyBox func- tion. However, to control its color, you need to edit read more..

  • Page - 250

    232 javascript & jquery: the missing manual Tutorial: FancyBox Photo Gallery 1. In a text editor, open the file fancybox.html in the chapter07 folder. This file contains a simple group of thumbnail images. Each image is linked to a larger version of the photo, and all of the thumbnails are contained within a <div> tag with an ID of gallery. The first read more..

  • Page - 251

    233 chapter 7: improving your images Tutorial: FancyBox Photo Gallery <a href="../_images/large/slide1.jpg" rel="gallery"> The actual value you supply the rel attribute—gallery in this case—doesn’t matter. What’s important is that the value be the same for every image you wish to include in the group. 6. Add rel=“gallery” to each of the 5 read more..

  • Page - 252

    234 javascript & jquery: the missing manual Tutorial: FancyBox Photo Gallery overlayOpacity : .3, transitionIn: 'elastic', transitionOut: 'elastic', easingIn: 'easeInSine', easingOut: 'easeOutSine', titlePosition: 'outside' , cyclic: true }); Don’t forget to add a comma at the end of overlayOpacity : .3. When you set transitionIn and transitionOut properties read more..

  • Page - 253

    235 chapter 8 Improving Navigation Links make the web go around. Without the instant access to information pro- vided by linking from page to page and site to site, the web wouldn’t have gotten very far. In fact, it wouldn’t be a web at all. Since links are one of the most common and powerful pieces of HTML, it’s only read more..

  • Page - 254

    236 javascript & jquery: the missing manual Some Link Basics jQuery gives you great flexibility in selecting document elements. For example, the code $(‘a’) creates a jQuery selection of all links on a page. Furthermore, jQuery lets you refine your selections, so you can quickly select all the links within a particular area of a page. For example, you can read more..

  • Page - 255

    237 chapter 8: improving navigation Some Link Basics Line 1 selects all external links (page 146) then runs the each() function (page 147), which simply applies a function to each link (in other words, it “loops” through the list of links). In this case, lines 2–4 make up the function body. Line 2 retrieves the link’s href of the link read more..

  • Page - 256

    238 javascript & jquery: the missing manual Opening External Links in a New Window 4. Stop the link! This step is the most important. If you don’t stop the link, the web browser will simply leave the current page and go to the login web page. Here’s how to stop the link using the “return false” method. Assume that the link has an ID of read more..

  • Page - 257

    239 chapter 8: improving navigation Opening External Links in a New Window Manually adding target=“_blank” to each link that points outside your site takes a long time and is easy to forget. Fortunately, using JavaScript and jQuery, there’s a quick, easy method to force web browsers to open external links (or any links you want) in a new window or read more..

  • Page - 258

    240 javascript & jquery: the missing manual Creating New Windows The second line of code starts with a jQuery selector, which retrieves all links that start with http://. Then, the not() function removes any links start with your URL— in this example, links that point to http://www.sawmac.com. (The not() function is a useful way of excluding some elements read more..

  • Page - 259

    241 chapter 8: improving navigation Creating New Windows open(URL, name, properties) The open() method takes three arguments. The first is the URL of the page you wish to appear in the new open window—the same value you’d use for the href attribute for a link (http://www.google.com, /pages/map.html, or ../../portfolio.html, for exam- ple). The second argument is a read more..

  • Page - 260

    242 javascript & jquery: the missing manual Creating New Windows Figure 8-1: The different properties of a browser win- dow like scroll bars, toolbars, and resize handles are collectively called a browser’s chrome. Each browser has its own take on these properties, and web developers have little control over how they work or look. Don’t despair—when you create a new read more..

  • Page - 261

    243 chapter 8: improving navigation Creating New Windows • toolbar sets the visibility of the toolbar containing the navigation buttons, book- mark button, and other controls available to the particular browser. On Safari, the toolbar and location settings are the same: Turning on either one displays both the toolbar buttons and the location field. • location read more..

  • Page - 262

    244 javascript & jquery: the missing manual Creating New Windows • blur() forces the window to “lose focus.” That is, the window moves behind any already opened windows. It’s a way to hide an opened window, and web advertisers use it to create “pop under” ads—windows that open underneath any current windows, so when the visitor closes all of read more..

  • Page - 263

    245 chapter 8: improving navigation Opening Pages in a Window on the Page Tip: The jQuery ScrollTo plug-in provides a simple way to control document scrolling using JavaScript. Find out more about this plug-in at http://plug-ins.jquery.com/project/ScrollTo. Events that can open a new window In the short history of the web, pop-up windows have gotten a bad name. Unfortu- read more..

  • Page - 264

    246 javascript & jquery: the missing manual Opening Pages in a Window on the Page Figure 8-2: You can quickly create a page-within- a-page effect using the FancyBox jQuery plug-in. The <iframe> (sho rt for inline frame) is similar to old-school HTML frames, but you can insert an iframe anywhere in a page’s HTML. By setting the dimensions of the iframe read more..

  • Page - 265

    247 chapter 8: improving navigation Opening Pages in a Window on the Page 1. Download the FancyBox files from http://fancybox.net. See step 2 on page 224 for more information on which files you’ll need. 2. Attach the FancyBox CSS file to your web page. FancyBox uses some, ahem, fancy CSS to achieve its page-within-a-page look, and it won’t look or read more..

  • Page - 266

    248 javascript & jquery: the missing manual Opening Pages in a Window on the Page }); // end fancybox }); // end ready </script> You can also use percentage values so the box is a percentage of the total width and height of the browser window—this is a good way to make sure the box takes advantage of very large screens for some read more..

  • Page - 267

    249 chapter 8: improving navigation Basic, Animated Navigation Bar 5. Near the top of the file, click in the empty line after the $(document).ready() function and add the code listed on lines 3–7: 1 <script> 2 $(document).ready(function() { 3 $('.iframe').fancybox({ 4 width : '90%', 5 height : '90%', 6 read more..

  • Page - 268

    250 javascript & jquery: the missing manual Basic, Animated Navigation Bar Figure 8-3: Navigating a website filled with many pages and sections can be confusing. A navigation bar with drop-down menus is an elegant way to simplify the presentation of your site’s links. It lets you include many navigation options and reduce clutter on your page. Fortunately, with just a read more..

  • Page - 269

    251 chapter 8: improving navigation Basic, Animated Navigation Bar </ul> </li> <li><a href="#">Gadgets </a> <ul> <li><a href="#">Gadget Basic</a></li> <li><a href="#">Gadget Standard</a></li> read more..

  • Page - 270

    252 javascript & jquery: the missing manual Basic, Animated Navigation Bar • Gadget Standard • Gadget Supreme • Gadget Supreme A • Gadget Supreme B • Time Machines Keep in mind that a nested list goes within the <li> tag of its parent item. For ex- ample, the <ul> tag containing the list items Gizmos, Gadgets, and Time Machines is contained within the read more..

  • Page - 271

    253 chapter 8: improving navigation Basic, Animated Navigation Bar margin: 0; padding: 0; list-style-type: none; } • #navigation a controls the appearance of each link. You can have fun with this style: Apply background colors, fonts, font color, border lines to make your but- tons standout. However, avoid setting margin and padding values read more..

  • Page - 272

    254 javascript & jquery: the missing manual Basic, Animated Navigation Bar There are a few subtleties that make this basic idea a bit more complicated. For example, pop-up menus that disappear the very instant the mouse moves off of its parent list item require precise mouse technique. It’s easy to mouse off a list item when trying to navigate to a read more..

  • Page - 273

    255 chapter 8: improving navigation Basic, Animated Navigation Bar To activate the menu, you first use jQuery to select the <ul> tag used for the main navigation bar—in this example, that tag has the ID navigation applied to it, so the code $(‘#navigation’) selects that tag, and the .navPlugin() applies the jQuery Navigation plug-in programming to read more..

  • Page - 274

    256 javascript & jquery: the missing manual Basic, Animated Navigation Bar PLUG-IN ALERT Other jQuery Plug-ins for Enhancing Page Navigation The jQuery Navigation plug-in is simple and effective, but there are a ton of other jQuery plug-ins for creating more advanced navigation. • The DD Mega Menu plug-in (http://dynamicdrive .com/dynamicindex1/ddmegamenu.htm) lets you create not just read more..

  • Page - 275

    257 chapter 9 Enhancing Web Forms Since the earliest days of the web, forms have made it possible for websites to collect information from their visitors. Forms can gather email addresses for a newsletter, collect shipping information to complete an online sale, or simply receive visitor feedback. Forms also require your site’s visitors to think: read more..

  • Page - 276

    258 javascript & jquery: the missing manual Understanding Forms Figure 9-1: A basic form can include many differ- ent types of controls, including text fields, radio buttons, checkboxes, menu lists, submit buttons, and so on. For a complete rundown on HTML form fields and how to use them, visit www.w3schools.com/ html/html_forms.asp. You create the actual form controls—the read more..

  • Page - 277

    259 chapter 9: enhancing web forms Understanding Forms <option>Mars</option> <option>Alpha Centauri</option> <option>You've never heard of it</option> </select> </div> <div class="labelBlock">Would you like to receive annoying e-mail from us?</div> <div class="indent"> <input type="radio" read more..

  • Page - 278

    260 javascript & jquery: the missing manual Understanding Forms Since the <input> tag is used for radio buttons, text fields, password fields, check- boxes, submit buttons, reset buttons, and hidden fields, you can’t just select the <input> tag. I nstead, you need to be able to find a particular type of input tag. Fortunately, jQuery has taken the burden read more..

  • Page - 279

    261 chapter 9: enhancing web forms Understanding Forms $(':checked') Even better, you can use this filter to find which radio button within a group has been selected. For example, say you have a group of radio buttons (“Pick a delivery method”) with different values (UPS, USPS, and FedEx, for instance) and you want to find the value of the radio button read more..

  • Page - 280

    262 javascript & jquery: the missing manual Understanding Forms form field’s value. For example, say you have a field for collecting a user’s email address with an ID of email. You can find the contents of that field like this: var fieldValue = $('#email').val(); You can set the value of a field simply by passing a value to the val() function. read more..

  • Page - 281

    263 chapter 9: enhancing web forms Understanding Forms radio buttons and checkboxes require visitors to make a choice by selecting a partic- ular value. You saw on page 260 how you can use the :checked filter to find checked radio buttons and checkboxes, but once you find it, you need a way to determine the status of a particular button or box. In read more..

  • Page - 282

    264 javascript & jquery: the missing manual Understanding Forms when the form is submitted—in other words, a visitor can’t leave the field blank. You can do so by adding a submit event to the form, and checking the value of the field before the form is submitted. If the field is empty, you want to let the visitor know and stop the read more..

  • Page - 283

    265 chapter 9: enhancing web forms Understanding Forms <input name="username" type="text" id="username" value="Please type your user name"> This code creates a text field on the form with the text “Please type your user name” inside it. This technique lets you provide instructions as to how the visitor is sup- posed to fill out the field. read more..

  • Page - 284

    266 javascript & jquery: the missing manual Understanding Forms Blur When you tab out of a field or click outside of the currently focused field, the brows- er triggers a blur event. This event is commonly used with text and textarea fields to run a validation script when someone clicks or tabs out of a field. For example, say you have a long read more..

  • Page - 285

    267 chapter 9: enhancing web forms Understanding Forms Like other events, you can use jQuery’s click() function to assign a function to a form field’s click event: $(':radio').click(function() { //function will apply to every radio button when clicked }); Note: The click event also applies to text fields, but it’s not the same as the focus event. Focus is read more..

  • Page - 286

    268 javascript & jquery: the missing manual Adding Smarts to Your Forms Figure 9-3: A form menu’s change event lets you do interesting things when a visitor selects an option from a menu. In this case, selecting an op- tion from the top menu dynamically changes the options presented in the second menu. Choose a product from the top menu, and the second menu displays read more..

  • Page - 287

    269 chapter 9: enhancing web forms Adding Smarts to Your Forms they can type? Why not just place the cursor in the field, ready to accept their login information immediately? With JavaScript, that’s a piece of cake. The secret lies in focus, which isn’t just an event JavaScript can respond to but a command that you can issue to place the cursor read more..

  • Page - 288

    270 javascript & jquery: the missing manual Adding Smarts to Your Forms To “turn off ” a form field that shouldn’t be filled out, you can disable it using Java- Script. Disabling a field means it can’t be checked (radio buttons and checkboxes), typed into (text fields), selected (menus), or clicked (submit buttons). To disable a form field, simply read more..

  • Page - 289

    271 chapter 9: enhancing web forms Adding Smarts to Your Forms FREQUENTLY ASKED QUESTION Stopping Multiple Submissions Sometimes I get the same form information submitted more than once. How can I prevent that from happening? Web servers aren’t always the fastest creatures…and nei- ther is the Internet. Often, there’s a delay between the time a visitor presses a form’s read more..

  • Page - 290

    272 javascript & jquery: the missing manual Tutorial: Basic Form Enhancements Note: jQuery’s hide() and show() functions (as well as other functions for revealing and concealing elements) are discussed on page 187. One usability benefit of hiding a field (as opposed to just disabling it) is that it makes the layout of the form simpler. After all, a disabled field read more..

  • Page - 291

    273 chapter 9: enhancing web forms Tutorial: Basic Form Enhancements Note: See the note on page 29 for information on how to download the tutorial files. Focusing a Field The first field on this tutorial’s order form page collects the name of the person plac- ing the order (see Figure 9-4). To make using the form easier to fill out, you’ll place the read more..

  • Page - 292

    274 javascript & jquery: the missing manual Tutorial: Basic Form Enhancements 7 <label for="mastercard">MasterCard</label> 8 </div> 9 <div id="creditCard" class="indent"> 10 <div> 11 <label for="cardNumber" class="label">Card Number</label> 12 <input type="text" read more..

  • Page - 293

    275 chapter 9: enhancing web forms Tutorial: Basic Form Enhancements To disable the fields, all you have to do is set the disabled attribute to true (see page 269). However, this doesn’t do anything to the text labels (“Card Number” and “Expiration Date”). Even though the fields themselves are disabled, those text labels remain bright and bold, read more..

  • Page - 294

    276 javascript & jquery: the missing manual Tutorial: Basic Form Enhancements The selector $(‘#visa, #mastercard’) selects both of the other radio buttons (see lines 4 and 6 of the HTML on page 273). Notice that to remove the background color and text colors added by clicking the PayPal button, you simply pass an empty string as the color value: read more..

  • Page - 295

    277 chapter 9: enhancing web forms Tutorial: Basic Form Enhancements fields if they don’t have to. You’ll frequently see a “Same as billing” checkbox on forms like these to indicate that the information is identical for both sets of fields. However, wouldn’t it be even more useful (not to mention cooler) if you could com- pletely hide the read more..

  • Page - 296

    278 javascript & jquery: the missing manual Form Validation 11 .css('backgroundColor',''); 12 $('#creditCard label').css('color',''); 13 }); // end click 14 $('#hideShip').click(function() { 15 if ($(this).attr('checked')) { 16 $('#shipping').slideUp('fast'); 17 } else { 18 read more..

  • Page - 297

    279 chapter 9: enhancing web forms Form Validation Figure 9-5: When you sign up for a Yahoo account, you’re faced with a sea of red error mes- sages (circled) if you fail to fill out the form properly. Checking to make sure a text field has been filled out is easy. As you read on page 261, you can simply access the form’s value property (using read more..

  • Page - 298

    280 javascript & jquery: the missing manual Form Validation jQuery Validation Plug-in The Validation plug-in (http://bassistance.de/jquery-plugins/jquery-plugin-validation/) is a powerful but easy-to-use jQuery plug-in created by Jörn Zaefferer. It can check a form to make sure all required fields have been filled out, and check to make sure that visitor input meets read more..

  • Page - 299

    281 chapter 9: enhancing web forms Form Validation 5. Apply the validate() function to the form. The plug-in includes a function that makes all of the magic happen: validate(). To apply it, you first use jQuery to select the form, and then attach the function to that selection. For example, say you have a form with an ID of signup applied read more..

  • Page - 300

    282 javascript & jquery: the missing manual Form Validation the validation terms is present, and if so, to apply the particular validation rule to that field. For example, say you have a text field to collect a person’s name. The basic HTML might look like this: <input name="name" type="text"> To tell the plug-in that the field is read more..

  • Page - 301

    283 chapter 9: enhancing web forms Form Validation For example, say you have a field asking for someone’s date of birth. This informa- tion is not only required, but should also be in a date format. The HTML for that field could look like this: <input name="dob" type="text" class="required date" > Notice that the class names—required read more..

  • Page - 302

    284 javascript & jquery: the missing manual Form Validation Adding validation rules and error messages by adding class names and titles to fields is easy, and it works great. But sometimes you may have more complicated valida- tion needs; the Validation plug-in offers a second, more advanced method of adding validation to a form. For example, you may want to read more..

  • Page - 303

    285 chapter 9: enhancing web forms Form Validation Tip: You can combine the basic validation method described on page 281 and the advanced method described here on the same form. For fields that have just one validation rule and error message, you can use the simple method since it’s fast, and just use the advanced method for more complicated validation. The tutorial on read more..

  • Page - 304

    286 javascript & jquery: the missing manual Form Validation $('#signup').validate({ rules: { name: 'required' } }); // end validate() In this case, the field is named name, and the rule specifies that the field is required. To apply more than one validation rule to a form field, you must create another ob- ject for that field. For example, read more..

  • Page - 305

    287 chapter 9: enhancing web forms Form Validation $('#signup').validate({ rules: { name: 'required', email: { required:true, email:true }, birthday: { date:true, required:true } } }); // end validate() As mentioned earlier, one of the most powerful and useful things you can read more..

  • Page - 306

    288 javascript & jquery: the missing manual Form Validation • range. Combines min and max to specify both the smallest and largest numbers that the field must contain. For example, to make sure a field contains at least 10 but no more than 1,000, use this: range:[10,1000] • equalTo. Requires that a field’s contents match another field. For read more..

  • Page - 307

    289 chapter 9: enhancing web forms Form Validation POWER USERS’ CLINIC Validating with the Server While JavaScript validation is great for quickly checking user input, sometimes you need to check in with the server to see if a field is valid. For example, say you have a sign-up form that lets visitors create their own username for use on the forums of your site. No two read more..

  • Page - 308

    290 javascript & jquery: the missing manual Form Validation $('#signup').validate({ rules: { password: { required:true, rangelength:[8,16] }, confirm_password: { equalTo:'#password' } }, // end of rules messages: { password: { required: "Please type the password you'd like to use.", read more..

  • Page - 309

    291 chapter 9: enhancing web forms Validation Tutorial label.error { color: #F00; font-weight: bold; } Since the Validation plug-in also adds an error class to the invalid form field, you can create CSS styles to format those as well. For example, to place a red border around invalid fields, you can create a style like this: input.error, select.error, read more..

  • Page - 310

    292 javascript & jquery: the missing manual Validation Tutorial Note: See the note on page 29 for information on how to download the tutorial files. Basic Validation In this tutorial, you’ll get started with the Validation plug-in by applying the basic validation methods described on page 281. Then you’ll learn more complex valida- tion procedures using the advanced read more..

  • Page - 311

    293 chapter 9: enhancing web forms Validation Tutorial Congratulations—you’ve ju st added validation to your form using the basic method discussed on page 281. Next, you’ll add another validation rule for the “date of birth” field. Note: If you don’t see an error message and instead get a page with the headline “Form Processed,” the validation didn’t read more..

  • Page - 312

    294 javascript & jquery: the missing manual Validation Tutorial 7. Locate the HTML for the opening select tag—<select name=“planet” id=“planet”>—and add cla ss and title attributes so that the tag looks like this (changes are in bold): <select name="planet" id="planet" class="required" title="Please choose a planet."> You can validate menus just read more..

  • Page - 313

    295 chapter 9: enhancing web forms Validation Tutorial required: true, email: true } } // end rules }); // end validate() Here, you’ve added another object literal. The first part, email, is the name of the field you wish to validate and matches the field’s name in the HTML. Next, two validation methods are specified—the field is read more..

  • Page - 314

    296 javascript & jquery: the missing manual Validation Tutorial “hello” in to the email field. This time you should get the “This is not a valid email address” error. If you don’t get any error messages and, instead, end up on the “Form Pro- cessed!” page, there’s a JavaScript error somewhere in your code. The most likely culprit is a missing comma read more..

  • Page - 315

    297 chapter 9: enhancing web forms Validation Tutorial Don’t forget the comma on line 5. At this point, you should be feeling comfortable adding rules and error messages. Next you’ll add validation for the checkboxes and radio buttons. Validating Checkboxes and Radio Buttons Checkboxes and radio buttons usually come in groups, and typically, adding valida- tion to several read more..

  • Page - 316

    298 javascript & jquery: the missing manual Validation Tutorial Figure 9-9: The Validation plug-in places error messages after the invalid form field. In the case of checkboxes and radio buttons, that looks awful. In order to place the error mes- sage elsewhere, you need to provide some instruction to the plug-in’s validate() function. The Validation plug-in places the error read more..

  • Page - 317

    299 chapter 9: enhancing web forms Validation Tutorial to place. The function receives both the error message and the form element the error applies to, so you can use a conditional statement (page 79) to check whether the form field is either a radio button of a checkbox. If it is, the error message is added to the end of the element containing read more..

  • Page - 318

    300 javascript & jquery: the missing manual Validation Tutorial the form field they apply to. You can make all of those formatting changes with a little simple CSS. 1. Near the top of the validation.html file, click on the blank line between the opening <style> and closing </style> tags. This page has an empty style sheet into which you’ll add read more..

  • Page - 319

    301 chapter 10 Expanding Your Interface A web page can feel like a long one-page brochure. Visitors are overwhelmed if there seem to be acres of text and pictures to scroll through, and they are unable to quickly get the information they need. It’s up to you to provide your visitors tools to find what they’re after. Using JavaScript and read more..

  • Page - 320

    302 javascript & jquery: the missing manual Organizing Information in Tabbed Panels Figure 10-1: Tabbed panels are common on e-com- merce sites, where information is often displayed in separate panels. This example (just a fragment of a complete web page) presents a product overview, product specifications, and shipping information in separate panels, so visitors can click a tab to read more..

  • Page - 321

    303 chapter 10: expanding your interface Organizing Information in Tabbed Panels <ul class="tabs"> <li><a href="#panel1">Overview</a></li> <li><a href="#panel2">Specifications</a></li> <li><a href="#panel3">Shipping</a></li> </ul> The links inside the list items are in-page links pointing to IDs assigned read more..

  • Page - 322

    304 javascript & jquery: the missing manual Organizing Information in Tabbed Panels <div class="panel" id="panel2"> <!-- put content here --> </div> <div class="panel" id="panel3"> <!-- put content here --> </div> read more..

  • Page - 323

    305 chapter 10: expanding your interface Organizing Information in Tabbed Panels .tabs a { display: block; text-decoration: none; padding: 3px 5px; } Of course, you’ll probably want to add more properties to really make the tabs look great: background-color to give the tabs life, fonts, font colors and sizes to make the tab text read more..

  • Page - 324

    306 javascript & jquery: the missing manual Organizing Information in Tabbed Panels • Panel content. To style the content inside of a panel, you can use descendent selectors to target the tags inside each panel div. For example, if you want to make a <h2> tag inside an orange panel displaying the Arial font face, you could create this style: read more..

  • Page - 325

    307 chapter 10: expanding your interface Organizing Information in Tabbed Panels Figure 10-2: The HTML structure for tabbed pan- els is really pretty simple: a div tag, an unordered list, some links, and more div tags. <div class=”tabbedPanels”> <div class=”panel” id=”panel1”> <div class=”panel” id=”panel2”> <div class=”panel” id=”panel3”> <ul class=”tabs”> read more..

  • Page - 326

    308 javascript & jquery: the missing manual Organizing Information in Tabbed Panels Note: To make the CSS for the tabbed panels as clear as possible, we’ve put it directly in this page’s HTML in an internal stylesheet. If you want to reuse this CSS for your own tabbed panels, it’s best to put it into the main external stylesheet used by your site. The jQuery read more..

  • Page - 327

    309 chapter 10: expanding your interface Organizing Information in Tabbed Panels Line 3 hides the panels. Because each panel is a <div> tag with the class of panel, $(‘.panel’) selects them all and jQuery’s .hide() function (page 187) hides them. You need to do this because otherwise, when you open one panel, the previous panel will still be visible. Line read more..

  • Page - 328

    310 javascript & jquery: the missing manual Organizing Information in Tabbed Panels Now that the programming is in place, if you trigger a click when the page loads, then you can run this function, hide the panels, select a tab and display its associated panel. Fortunately, jQuery makes it easy to simulate any event and trigger an event handler. 7. After the read more..

  • Page - 329

    311 chapter 10: expanding your interface Organizing Information in Tabbed Panels 9. Save the page and try it out in a web browser. The completed tutorial should look like Figure 10-3. You can add more tabs and more panels simply by inserting additional list items to the unordered list containing links that point to new div tags for the new panels. Note: read more..

  • Page - 330

    312 javascript & jquery: the missing manual Adding a Content Slider to Your Site UP TO SPEED The jQuery UI Project You’ll find a more advanced version of tabbed panels as part of jQuery UI. An official project of the jQuery team, jQuery UI aims to provide plug-ins that solve basic user interface problems: accordions, tabs, dialog boxes, calen- dar widgets, and draggable read more..

  • Page - 331

    313 chapter 10: expanding your interface Adding a Content Slider to Your Site Figure 10-4: To minimize on-screen clutter, sites like Microsoft.com use content sliders (outlined in black) to display a single image or chunk of content at a time. In this example, the image outlined can slide out of sight to the left, revealing another image with more information. Using read more..

  • Page - 332

    314 javascript & jquery: the missing manual Adding a Content Slider to Your Site 5. Add <script> tags a nd the $(document).ready() function, and then call the AnythingSlider function: One of the pleasures of working with jQuery plug-ins is that they often require very little code to work. In this case, adding simple code to the page after the link to read more..

  • Page - 333

    315 chapter 10: expanding your interface Adding a Content Slider to Your Site <div id="slider"> </div> This is a <div> tag (an HTML tag meant to mark a region or division in a web page). This particular div represents the slider itself. Inside it, you’ll add more <div> tags, one for each slide you wish to display. 5. Inside the slider read more..

  • Page - 334

    316 javascript & jquery: the missing manual Adding a Content Slider to Your Site arrow button to move to the next slider to the right, the left arrow button to move back one slider, the numbered buttons to jump to a specific slider, and the start button to begin an automated slideshow. Figure 10-5: Using the AnythingSlider jQuery plug-in, you can read more..

  • Page - 335

    317 chapter 10: expanding your interface Adding a Content Slider to Your Site • Color of the navigation buttons. The numbered buttons at the bottom of the slid- er are normally green. If you don’t like that color, edit this long-winded style: div .anythingSlider.activeSlider .anythingControls ul a.cur, div.anythingSlider.active Slider .anythingControls ul a. Change read more..

  • Page - 336

    318 javascript & jquery: the missing manual Adding a Content Slider to Your Site Customizing the Slider Behavior You can make a lot of changes to the slider simply by editing the CSS file. But to make fundamental changes to how the slider works, you need to set a few options for the plug-in. To do this, you pass an object literal (page 145) to read more..

  • Page - 337

    319 chapter 10: expanding your interface Determining the Size and Position of Page Elements • Variable size slides. If each slide holds different amounts of content, you can make the slider window change size to grow or shrink the content of each slide. For example, say the first slide is a div with a single paragraph in it, while the second read more..

  • Page - 338

    320 javascript & jquery: the missing manual Determining the Size and Position of Page Elements want to make sure you don’t position an element outside the visible area of the browser window. • Height and width of the document. The document isn’t the same thing as the browser window and most often has a different height and width. The docu- ment read more..

  • Page - 339

    321 chapter 10: expanding your interface Determining the Size and Position of Page Elements • innerWidth() returns the width + the left and right padding; innerHeight() returns the CSS height + top and bottom padding: var divW = $('div').innerWidth(); // 340 var divH = $('div').innerHeight(); // 340 In the code above, the variables divW and divH hold the value 340—the read more..

  • Page - 340

    322 javascript & jquery: the missing manual Determining the Size and Position of Page Elements Figure 10-6: Width and height aren’t always straightforward when it comes to CSS. The CSS width and height properties only dictate the space dedicated to the content inside a tag. The overall height and width of an element on a page is calculated by combining width or read more..

  • Page - 341

    323 chapter 10: expanding your interface Determining the Size and Position of Page Elements $('#caption').css({ 'position' : 'absolute', 'left' : imagePosition.left, 'top' : imagePosition.top }); Note: The offset() and position() functions always return numbers representing the number of pixels from the left and top positions. That is, even if you use ems or read more..

  • Page - 342

    324 javascript & jquery: the missing manual Determining the Size and Position of Page Elements Figure 10-7: jQuery provides two functions that let you determine the top and left position of an element on the page. In the case where you have an absolutely positioned element ( #innerBox) inside another positioned element ( #outer- Box), the two functions will return different read more..

  • Page - 343

    325 chapter 10: expanding your interface Determining the Size and Position of Page Elements Figure 10-8: Often, a web page won’t completely fit inside a visitor’s browser window. The visitor then has to scroll to see other parts of the page. But even though you only see part of the document, it’s still always there in its entirety. Document Browser .scrollTop( ) read more..

  • Page - 344

    326 javascript & jquery: the missing manual Adding Tooltips Adding Tooltips Tooltips are a common way to provide supplemental information. They are small pop-up windows triggered when a visitor mouses over a link, word, photo or any page element. They’re often used to show a definition for a word, a caption for a pho- to, or even more detailed information like read more..

  • Page - 345

    327 chapter 10: expanding your interface Adding Tooltips Here’s the HTML for a basic tooltip: <div class="tooltip" id="aardvarkTooltip"> <h2>The Aardvark</h2> <p>A medium-sized, burrowing, nocturnal mammal native to Africa</p> </div> While you can put the tooltip divs just about anywhere in a page’s HTML (they’re hidden from view read more..

  • Page - 346

    328 javascript & jquery: the missing manual Adding Tooltips The CSS Each div has a class of tooltip, so adding a .tooltip style to the page’s stylesheet will format the overall look of the tooltip (such as background color, border, width, and so on). Here’s a basic style that’s already in the tutorial file: .tooltip { width: 25%; read more..

  • Page - 347

    329 chapter 10: expanding your interface Adding Tooltips tooltip content. If the tooltip content isn’t necessary information, and it’s OK if some visitors (including search engines) don’t see the tooltips, then go ahead and hide the tooltips in your CSS: .tooltip { display: none; } 2. Add a mouseover event handler to the trigger. This part is the read more..

  • Page - 348

    330 javascript & jquery: the missing manual Adding Tooltips 3. Locate the <p> tag below just below the <h1>Tooltips</h1> header abo ut halfway up the file. Wrap a few words in that paragraph in a <span> tag like this: <span class="trigger" data-tooltip="#tip1">accusamus et iusto</span> The class identifies this particular span as a trigger for a read more..

  • Page - 349

    331 chapter 10: expanding your interface Adding Tooltips 8. Inside the anonymous function you just added, type the bolded code below: 1 $('.trigger').mouseover(function() { 2 var ttLeft, 3 ttRight, 4 }); // end mouseover You start by creating two variables; ttLeft holds the left position of the tooltip, and ttTop the top position. The read more..

  • Page - 350

    332 javascript & jquery: the missing manual Adding Tooltips 10. Add another variable (line 5): 1 $('.trigger').mouseover(function() { 2 var ttLeft, 3 ttRight, 4 $this=$(this), 5 $tip = $($this.attr('data-tooltip')), 6 }); // end mouseover The variable $tip holds a jQuery selection of the tooltip. The code $($this read more..

  • Page - 351

    333 chapter 10: expanding your interface Adding Tooltips Lines 7 and 8 use the outerHeight() function (page 321) and outerWidth() func- tion (page 321) to retrieve the height (#2) and width (#3) (including padding and borders) of the trigger; while lines 9 and 10 get the width (#4) and height (#5) of the tooltip. Because you don’t want a tooltip to read more..

  • Page - 352

    334 javascript & jquery: the missing manual Adding Tooltips 12. Add lines 13-17 below to the mouseover function: 1 $('.trigger').mouseover(function() { 2 var ttLeft, 3 ttRight, 4 $this=$(this), 5 $tip = $($this.attr('data-tooltip')), 6 triggerPos = $this.offset(), 7 triggerH = read more..

  • Page - 353

    335 chapter 10: expanding your interface Adding Tooltips Note: The example in this section places the tooltip above the trigger, but you don’t have to do it that way. Feel free to play around with the programming to see if you can make the tooltip appear below or to the left or right of the trigger. Figure 10-11: You need to be careful when dynamically positioning read more..

  • Page - 354

    336 javascript & jquery: the missing manual Adding Tooltips Calculating the left position is a bit trickier than the right position. You need to know not only whether part of a tooltip is positioned off the right edge of the browser window, but by how much. For example, say a trigger’s left position is 850 pixels (marked as A in Figure 10-11), the read more..

  • Page - 355

    337 chapter 10: expanding your interface Adding Tooltips 13 if (triggerPos.top - tipH - scrollTop > 0 ) { 14 ttTop = triggerPos.top - tipH - 10; 15 } else { 16 ttTop = triggerPos.top + triggerH +10 ; 17 } 18 var overFlowRight = (triggerPos.left + tipW) - screenW; 19 read more..

  • Page - 356

    338 javascript & jquery: the missing manual Adding Tooltips 28 }).fadeIn(200); 29 }); // end mouseover 30 $('.trigger').mouseout(function () { 31 $('.tooltip').fadeOut(200); 32 }); // end mouseout The mouseout stuff is easy: Just fade out any visible tooltips when you mouse off the trigger. And that’s it. Save read more..

  • Page - 357

    4 Part Four: Ajax: Communication with the Web Server Chapter 11: Introducing Ajax Chapter 12: Flickr and Google Maps read more..

  • Page - 358

    read more..

  • Page - 359

    341 chapter 11 Introducing Ajax J avaScript is great, but it can’t do everything. If you want to display information from a database, dash off an email with results from a form, or just download additional HTML, you need to communicate with a web server. For these tasks, you usually need to load a new web page. For example, when you search a read more..

  • Page - 360

    342 javascript & jquery: the missing manual What Is Ajax? Figure 11-1: Google Maps ( http:// maps.google.com) was one of the first large sites to use Ajax to refresh page con- tent without loading new web pages. The site’s responsiveness is due to the fact that only the map data changes—the other parts of the page, like the logo, search box, search results sidebar, read more..

  • Page - 361

    343 chapter 11: introducing ajax Ajax: The Basics • Display new HTML content without reloading the page. For example, on a page that lists news headlines and displays the article when a visitor clicks a headline, you can save him the tiresome wait for a new page to load. Instead, the news story could appear right on the same web page, without the read more..

  • Page - 362

    344 javascript & jquery: the missing manual Ajax: The Basics Figure 11-2: The traditional way a web browser communicates with a server (top) involves requesting a file from the server and receiving a web page back. It’s a constant loading and reloading of web pages. With Ajax, the web browser requests only new informa- tion. The server returns the requested data, and the read more..

  • Page - 363

    345 chapter 11: introducing ajax Ajax: The Basics The XMLHttpRequest object was actually introduced in Internet Explorer 5 many years ago, but has gradually made its way into all the major web browsers. You’ll learn more about it on page 346. • JavaScript does most of the heavy lifting in Ajax. It sends a request to the web server, waits for a read more..

  • Page - 364

    346 javascript & jquery: the missing manual Ajax: The Basics There are many different combinations of web servers, application servers, and database servers. For example, you might use Microsoft’s IIS web server, with ASP.NET (application server) and SQL server (a database server). Or you can use Apache (a web server), PHP (an application server), and MySQL (a read more..

  • Page - 365

    347 chapter 11: introducing ajax Ajax: The Basics 1. Create an instance of the XMLHttpRequest object. This first step simply tells the web browser “Hey, I want to send some informa- tion to the web server, so get ready.” In its most basic form, creating an XML- HttpRequest object in JavaScript looks like this: var newXHR = new XMLHttpRequest(); read more..

  • Page - 366

    348 javascript & jquery: the missing manual Ajax: The Basics Usually, this function will manipulate the page’s content (that is, change the page’s DOM) by removing elements (for example, removing a form that was just submitted using Ajax), adding elements (a “form submitted successfully” mes- sage, or a new HTML table of database records), or changing read more..

  • Page - 367

    349 chapter 11: introducing ajax Ajax the jQuery Way In addition, most of the time, you’ll receive a text response, which is stored in the XHR object’s responseText property. This response could be a chunk of HTML, a simple text message, or a complex set of JSON data (see page 370). Finally, if the server responds with an XML file, it’s read more..

  • Page - 368

    350 javascript & jquery: the missing manual Ajax the jQuery Way Figure 11-3: The top set of images shows how links work—the typical method of accessing additional HTML. Click a link on a page (top left) and it loads a brand new page (top right). However, using Ajax and jQuery’s load() function, you can access the same HTML without leaving the cur- rent web page read more..

  • Page - 369

    351 chapter 11: introducing ajax Ajax the jQuery Way UP TO SPEED Learning the Ways of the Server Side Unless you’re using jQuery’s basic load() function (dis- cussed previously) to insert HTML from a page on the serv- er into the page in the web browser, you’ll need to have server-side programming to use Ajax. The main point of Ajax is to let JavaScript talk to read more..

  • Page - 370

    352 javascript & jquery: the missing manual Ajax the jQuery Way When using the load() function, you must be very careful with file paths. First, the URL you pass to the load() function is in relation to the current page. In other words, you use the same path as if you were linking from the current page to the HTML file you wish to load. read more..

  • Page - 371

    353 chapter 11: introducing ajax Ajax the jQuery Way fine—it’ll get any visitors to the news they’re after. That’s a good thing, because not everyone has JavaScript enabled in their browsers. In addition, if the only way to get to those news items is through JavaScript, search engines would skip over that valuable content. Figure 11-4: When you want read more..

  • Page - 372

    354 javascript & jquery: the missing manual Ajax the jQuery Way newslinks, so you can easily use jQuery to select each of those links and assign a click() function to them. 2. Click in the empty line inside the $(document).ready() function, and type: $('#newslinks a').click(function() { }); The $(‘#newslinks a’) is the jQuery way to select each of read more..

  • Page - 373

    355 chapter 11: introducing ajax Ajax the jQuery Way $('#newslinks a').click(function() { var url=$(this).attr('href'); $('#headlines').load(url); return false; }); This simple step tells the web browser, “Hey, web browser, don’t follow that link.” It’s one way of preventing a browser from following its normal behavior in response to an event. You can read more..

  • Page - 374

    356 javascript & jquery: the missing manual Ajax the jQuery Way $('#newslinks a').click(function() { var url=$(this).attr('href'); $('#headlines').load(url + ' #newsItem'); return false; }); As described on page 352, you can specify which part of a downloaded file you want the load() function to add to the page. To do that, you add a space after the read more..

  • Page - 375

    357 chapter 11: introducing ajax Ajax the jQuery Way $.get(url, data, callback); Or: $.post(url, data, callback); Unlike most other jQuery functions, you don’t add get() or post() to a jQuery selector—in other words, you’d never do something like this: $(‘#mainContent’) .get(‘products.php’). The two functions stand by themselves and aren’t connected with any read more..

  • Page - 376

    358 javascript & jquery: the missing manual Ajax the jQuery Way FREQUENTLY ASKED QUESTION GET or POST? The two methods for submitting data to a web server, GET and POST, seem pretty much the same. Which should I use? The answer really depends. In some cases, you don’t have a choice. For example, suppose you’re sending informa- tion to a server-side script that’s read more..

  • Page - 377

    359 chapter 11: introducing ajax Ajax the jQuery Way You need to be careful using this method, however, since some characters have spe- cial meaning when you insert into a query string. For instance, you use the & symb ol to include additional name/value pairs to the string; the = symbol assigns a value to a name. For example, the following query read more..

  • Page - 378

    360 javascript & jquery: the missing manual Ajax the jQuery Way Or, if you directly pass an object literal to .post(): var data = $.post('rankMovie.php', { rating: 5, user: 'Bob' } ); // end post jQuery’s serialize() function Creating a query string or object literal for an entire form’s worth of name/value pairs can be quite a read more..

  • Page - 379

    361 chapter 11: introducing ajax Ajax the jQuery Way When the web browser sends off a request to the server using the XMLHttpRequest object, it keeps listening for a response from the server. When the server responds, a callback function handles the server’s response. That function is passed several argu- ments that can be used by the function. First, and read more..

  • Page - 380

    362 javascript & jquery: the missing manual Ajax the jQuery Way Figure 11-6: On this page, a visitor clicks a link to rate the movie (top). By adding Ajax to the mix, you can submit the rating to the server without leaving the page. In fact, using the response from the server, you can update the page’s contents (bottom). <div id="message"> <a read more..

  • Page - 381

    363 chapter 11: introducing ajax Ajax the jQuery Way link behavior and prevents the web browser from unloading the current page and loading the linked-to page. Figure 11-7: This diagram shows how JavaScript and the web server interact. The get() function sends information to the server, while the callback function— process- Response()—handles the infor- mation returned read more..

  • Page - 382

    364 javascript & jquery: the missing manual Ajax the jQuery Way Note: If you want to add a star rating system to your site, there’s a great jQuery plug-in that handles most of the details available at http://www.wbotelhos.com/raty/. Finally, line 6 modifies the HTML on the web page using jQuery’s html() function (see page 138) by replacing the contents of the read more..

  • Page - 383

    365 chapter 11: introducing ajax Ajax the jQuery Way Tutorial: Using the get() Function In this tutorial, you’ll use Ajax to submit information from a login form. When a visitor supplies the correct user name and password, a message will appear letting her know she’s successfully logged in. If the login information isn’t correct, an error message will read more..

  • Page - 384

    366 javascript & jquery: the missing manual Ajax the jQuery Way Overview You’ll start with the form pictured in Figure 11-8. It includes fields for supplying a username and password to the server. When the form is submitted, the server at- tempts to verify that the user exists and the password matches. If the information supplied matches valid login read more..

  • Page - 385

    367 chapter 11: introducing ajax Ajax the jQuery Way The <form> tag has the ID login applied to it, so the jQuery selector— $(‘#login’)—selects that form, while the submit() function adds an event handler to the submit event. In other words, when a visitor tries to submit the form, the function you’re about to create will run. The next step read more..

  • Page - 386

    368 javascript & jquery: the missing manual Ajax the jQuery Way Note: The server-side page used in this tutorial isn’t a full-fledged login script. It does respond if the proper credentials are supplied, but it’s not something you could use to actually password-protect a site. There are many ways to effectively password protect a site, but most require setting up a read more..

  • Page - 387

    369 chapter 11: introducing ajax Ajax the jQuery Way doesn’t remove the first error message, it just adds the message a second time. That doesn’t look right at all. You have several ways to deal with this problem. You could, for example, insert an empty div—<div id=“f ailMessage”>—below the form. Then simply replace its HTML when the login read more..

  • Page - 388

    370 javascript & jquery: the missing manual JSON the length attribute of the results. If jQuery couldn’t find any matching elements, the length attribute is 0. In other words, $(‘#fail’) tries to find an element with the ID fail. If jQuery can’t find it—in other words, the error message hasn’t yet been written to the page—then the length read more..

  • Page - 389

    371 chapter 11: introducing ajax JSON Note: Another type of JSON, known as JSONP, lets you request data from other domains, so you can, for example, request images from Flickr (www.flickr.com) and display them on a page on your own site. (As mentioned in the note on page 351, usually you can only make an Ajax request to your own domain.) You’ll see JSONP in action read more..

  • Page - 390

    372 javascript & jquery: the missing manual JSON Note: PHP 5.2 has a built-in function —json_encode—to make it easy to create a JSON object out of a traditional PHP array. So for AJAX applications, you can take a PHP array and quickly convert to a JSON object to send back to the awaiting JavaScript code in the web browser. Visit www.php.net/manual/en/ function.json-encode.php read more..

  • Page - 391

    373 chapter 11: introducing ajax JSON The same is true with a JSON object that’s returned by the web server. For example, take the following getJSON() example and callback function: $.getJSON('contacts.php','contact=123',processContacts); function processContacts(data) { } Assuming that the server returned the JSON example on page 371, that JSON object is assigned to the read more..

  • Page - 392

    374 javascript & jquery: the missing manual JSON The limit=2 is the information sent to the server, and indicates how many contacts should be returned. The web server would then return two contacts. Say the contact info for the first person matched the example above (Frank Smith), and a second set of contact information was another JSON object like this: { read more..

  • Page - 393

    375 chapter 11: introducing ajax JSON You pass the JSON object, and an anonymous function (page 148) to the each() function. That anonymous function receives the name and value of each item in the JSON object. Here’s how the JSON object would look in use in the current example: 1 $.getJSON('contacts.php','limit=2',processContacts); 2 function read more..

  • Page - 394

    376 javascript & jquery: the missing manual JSON Figure 11-10: You can use jQuery’s each() function to loop through a JSON object to perform tasks on nested objects. You can also use the each() function to loop through arrays. To learn more about this useful function, visit http://docs .jquery.com/Utilities/jQuery .each#objectcallback. function processContacts(data) { var read more..

  • Page - 395

    377 chapter 12 Flickr and Google Maps In the previous chapter, you learned the basics of Ajax: what it is, how it works, and how jQuery can simplify the process of Ajax programming. Since Ajax is all about the two-way communication between web browser and web server, under- standing server-side programming is necessary if you really want to harness Ajax’s read more..

  • Page - 396

    378 javascript & jquery: the missing manual Adding a Flickr Feed to Your Site You can’t request just any bit of information that you’d like from another site, how- ever. For JSONP to work, the foreign site must be set up to respond with JSONP. Most sites aren’t set up to send information this way, but many of the big sites like read more..

  • Page - 397

    379 chapter 12: flickr and google maps Adding a Flickr Feed to Your Site Flickr gives you a couple of ways to retrieve photos and related information. The most powerful, but also most complex, method is to use Flickr’s API to search for photos. This method requires that you sign up at Flickr and get a special API key (a string of numbers read more..

  • Page - 398

    380 javascript & jquery: the missing manual Adding a Flickr Feed to Your Site To use multiple IDs, separate each with a comma. Note that you can only use multiple IDs for retrieving individual accounts: You can’t use the group feed and retrieve photos from multiple groups. Tip: If you know someone’s Flickr user name, you can get his Flickr ID using read more..

  • Page - 399

    381 chapter 12: flickr and google maps Adding a Flickr Feed to Your Site Note: You can only search for tags on Flickr’s public photo feed (www.flickr.com/services/feeds/docs/ photos_public/). You can’t, for example, search for photos with a particular tag or tags from a group (like the Flickr Web Design group). Flickr’s feed service provides options that let you search read more..

  • Page - 400

    382 javascript & jquery: the missing manual Adding a Flickr Feed to Your Site { firstName : 'Bob', lastName : 'Smith' } In this code, firstName acts like a key with a value of Bob—a simple string value. However, the value can also be another object (see Figure 11-10 on page 376), so you can often end up with a complex nested read more..

  • Page - 401

    383 chapter 12: flickr and google maps Tutorial: Adding Flickr Images to Your Site (see line 2 on page 381). Then, to access the title of the feed, you’d access the “title” property of the “data” object like this: data.title The most important part of the feed is the “items” property (line 7), which contains additional objects, each containing read more..

  • Page - 402

    384 javascript & jquery: the missing manual Tutorial: Adding Flickr Images to Your Site Tip: If you want to retrieve the photos from a Flickr group, like the Web Design Group, then change the URL in step 2 to: http://api.flickr.com/services/feeds/groups_pool.gne?id=37996591093@N01 and the ID to the ID of the Flickr group. Next you’ll put these variables together to read more..

  • Page - 403

    385 chapter 12: flickr and google maps Tutorial: Adding Flickr Images to Your Site and an anonymous function. The $.each() function then loops through the ar- ray or the object literal and runs the anonymous function once for each item. That anonymous function receives two arguments (i and photo in the code in this step), which are variables that contain read more..

  • Page - 404

    386 javascript & jquery: the missing manual Tutorial: Adding Flickr Images to Your Site $('#photos').append(photoHTML); }); // end each The $(‘#photos’) part selects an already existing <div> tag on the page, while the append() function (discussed on page 139) adds the HTML to the end of that div. In other words, each time through read more..

  • Page - 405

    387 chapter 12: flickr and google maps Adding Google Maps to Your Site 11. Save the page and preview it in a web browser. Now you should see 20 neatly aligned, square thumbnails (see Figure 12-1). Click a thumbnail to see a larger image on Flickr’s site. A working version of this tutorial—complete_flickr.html—is av ailable in the chapter12 folder. Note: read more..

  • Page - 406

    388 javascript & jquery: the missing manual Adding Google Maps to Your Site POWER USERS’ CLINIC Going Further with jQuery and Ajax There are loads of other jQuery plug-ins that can make Ajax development go faster. In some cases, you need to provide the server-side programming—the plug-in just takes care of the JavaScript part. A few other programs supply the ba- sic read more..

  • Page - 407

    389 chapter 12: flickr and google maps Adding Google Maps to Your Site Note: GoMap uses version 3 of the Google Maps API (Application Programming Interface). The older Google Maps API required you to sign up at Google and get a unique key to use Google Maps on your site. Fortunately, you no longer have to sign up with Google to add maps to your site. 2. Attach read more..

  • Page - 408

    390 javascript & jquery: the missing manual Adding Google Maps to Your Site Setting a Location for the Map A Google Map has a center point as defined by numbers that represent the location’s longitude and latitude. If you want to center your map on a place—such as your business’s address or the location of your next birthday party—you need to read more..

  • Page - 409

    391 chapter 12: flickr and google maps Adding Google Maps to Your Site In fact, you can use anything that works in the Google Maps search box (http:// maps.google.com) as the address element, even the names of well-known land- marks like “Kennedy Space Center” or “Eiffel Tower.” However, Google may not always be able to locate an address, and addresses read more..

  • Page - 410

    392 javascript & jquery: the missing manual Adding Google Maps to Your Site Set the maptype option to one of the following values: ‘HYBRID’, ‘ROADMAP’, ‘SATELLITE’, or ‘TERRAIN’. For example: maptype: 'TERRAIN' • Add a scale marker. It’s common on printed maps to have some kind of scale listed on the map: 1" equals 1 mile, for exa mple. A read more..

  • Page - 411

    393 chapter 12: flickr and google maps Adding Google Maps to Your Site mapTypeControl : false If you do like the map type buttons, you can control the style of those buttons and their position. You give the mapTypeControlOptions item an object literal composed of a position setting and a style. The possible values for placing the map type controls on the read more..

  • Page - 412

    394 javascript & jquery: the missing manual Adding Google Maps to Your Site This code represents one marker and, at its most basic, is composed of a latitude, longitude, and title for the marker (the title is the text that appears when a visitor mouses over the marker). By adding additional object literals to the array, you can add more markers to the map. read more..

  • Page - 413

    395 chapter 12: flickr and google maps Adding Google Maps to Your Site You can also add a marker after the map is created. This technique is handy if you don’t want a marker in the center of the map: For example, you might want to have a map of a park, and highlight various points of interest in the park with markers. You’ll want the park read more..

  • Page - 414

    396 javascript & jquery: the missing manual Adding Google Maps to Your Site latitude : 45, longitude : -122, zoom : 15 }); // end goMap $.each(markers,function(i,marker) { $.goMap.createMarker(marker); }); // end each In addition, you might want to remove markers (for example, a button that says Hide Markers). GoMap includes a clearMarkers() function. read more..

  • Page - 415

    397 chapter 12: flickr and google maps Adding Google Maps to Your Site Adding Information Windows to Markers You can also add a pop-up bubble (called an information window) to each marker. To do that, add another item to the object literal for each marker named html con- taining yet another object literal with the property’s content and popup. For example: read more..

  • Page - 416

    398 javascript & jquery: the missing manual Adding Google Maps to Your Site You’ve just created a placeholder, where the GoMap plug-in will eventually add a Google Map. Next, you’ll add a CSS style to set the height and width of the map. 3. At the top of the file is an internal style sheet; add a CSS rule, just after the opening <style> tag, type : read more..

  • Page - 417

    399 chapter 12: flickr and google maps Adding Google Maps to Your Site 8. Edit the script by adding a comma after the longitude option and inserting a zoom setting (changes are in bold): $('#map').goMap({ latitude : 45.53940, longitude : -122.59025, zoom : 16 }); // end goMap You can zoom completely out (0), or in to street read more..

  • Page - 418

    400 javascript & jquery: the missing manual Adding Google Maps to Your Site 12. Edit the code you typed in the last step to add an information window (changes in bold): $.goMap.createMarker({ latitude : 45.53743, longitude : -122.59473, title : 'hole1' , html : { content : read more..

  • Page - 419

    5 Part Five: Tips, Tricks, and Troubleshooting Chapter 13: Getting the Most from jQuery Chapter 14: Going Further with Java Script Chapter 15: Troubleshooting and Debugging read more..

  • Page - 420

    read more..

  • Page - 421

    403 chapter 13 Getting the Most from jQuery jQuery greatly simplifies JavaScript programming, and provides web designers with a tool that lets them add sophisticated interactivity quickly and easily. But jQuery isn’t always simple, and you need a certain amount of knowledge to use it to its full extent. In this chapter, you’ll learn how to take jQuery read more..

  • Page - 422

    404 javascript & jquery: the missing manual Useful jQuery Tips and Information In practice, you can use either jQuery() or $(); it’s your choice. However, since $() is faster to type, you’ll probably want to stick with it (as most programmers do). Note: Another JavaScript library named Prototype (www.prototypejs.org) also uses $(). If you happen to also read more..

  • Page - 423

    405 chapter 13: getting the most from jquery Useful jQuery Tips and Information Storing a selection into a variable is also very common when using events. As you’ll recall from page 149, when you are inside an event function, the variable $(this) re- fers to the element the event is applied to. However, each time you use $(this) you are calling the read more..

  • Page - 424

    406 javascript & jquery: the missing manual Useful jQuery Tips and Information different append operations. All of this processing is actually quite taxing on a web browser, and reducing the number of times you have to modify the DOM can sig- nificantly improve the performance of a page. In this example, you can reduce the number of append operations to just read more..

  • Page - 425

    407 chapter 13: getting the most from jquery Using the jQuery Docs $('#main a') than this selector: $('a') • Use the .find() function. jQuery includes a function for finding elements within a selection. It works kind of like a descendent selector in that it locates tags inside of other tags. You’ll read more about this function on page 414, but in read more..

  • Page - 426

    408 javascript & jquery: the missing manual Using the jQuery Docs Figure 13-1: The main jQuery docs page contains links to lots of useful information, but the ones that will help you figure out all of the functions jQuery offers are listed under the API heading in the main area of the page (outlined on right) or on the left sidebar (outlined on left). You’ll find read more..

  • Page - 427

    409 chapter 13: getting the most from jquery Using the jQuery Docs • Selectors (http://api.jquery.com/category/selectors/) provides access to some of the most helpful jQuery functions. This page is worth visiting often since it lists the many different ways to use jQuery to select page elements. You learned about many of these in Chapter 4, but you’ll find read more..

  • Page - 428

    410 javascript & jquery: the missing manual Using the jQuery Docs • The Ajax category (http://api.jquery.com/category/ajax/) lists functions related to dynamically updating a page based on information sent to or received from a web server. You’ll learn about Ajax in Part 4 of this book. • Utilities (http://api.jquery.com/category/utilities/). jQuery also provides read more..

  • Page - 429

    411 chapter 13: getting the most from jquery Using the jQuery Docs • Internals (http://api.jquery.com/category/internals/) are a handful of functions of various usefulness. The .jquery property, for example, returns the version of jQuery in use on the page: // open alert box with version number alert($().jquery); // 1.6.2, for example You can lead a long, happy life without read more..

  • Page - 430

    412 javascript & jquery: the missing manual Using the jQuery Docs Figure 13-2: The docs page for each jQuery function lists all the different ways you can use a function. In this case, listed under Contents: you’ll see that you can pass the .css() function either a single argument (#1) or two arguments (#2). The function behaves differently depending on which of read more..

  • Page - 431

    413 chapter 13: getting the most from jquery Traversing the DOM jQuery functions working in this way as both “getters” (t hat is, they retrieve infor- mation about an element) and “setters” (t hat is, they set the value of a particular property for an element). The docs page will describe each use of the function and usually provides working examples read more..

  • Page - 432

    414 javascript & jquery: the missing manual Traversing the DOM As you read on page 187, the fadeTo() function takes a duration and an opacity value as arguments. So this code first fades all of the images to 30% opacity in 500 milli- seconds, and then fades it back to 100% opacity in 250 milliseconds (see the file find .html in the chapter07 read more..

  • Page - 433

    415 chapter 13: getting the most from jquery Traversing the DOM You use .find() to select a descendent (a tag inside another tag) of the current selection. So in the example pictured in Figure 13-3, you could use .find() on a selection including the div to select either the <a> tags o r the <img> tags. Note: See the previous page to read about read more..

  • Page - 434

    416 javascript & jquery: the missing manual Traversing the DOM In this example, hovering over a link adds an outline around that link, then selects the link’s parent (the div) and applies a background color. Mousing off the link removes both the outline and background color (see page 171 for more information on the .hover() event). (See the file read more..

  • Page - 435

    417 chapter 13: getting the most from jquery Traversing the DOM The .siblings() function also can take an argument—the name of a selector—to limit the selected siblings to a certain type of tag. For example, say inside the <div> tag pictured in Figure 13-3, there’s a headline and introductory paragraph prior to the links. Since the headline and read more..

  • Page - 436

    418 javascript & jquery: the missing manual Traversing the DOM POWER USERS’ CLINIC Putting an .end() to DOM Traversal In order to get the most done while writing the least amount of code, jQuery lets you chain functions together. Chaining is discussed on page 137, but in a nutshell it lets you select some pages elements, do one thing to them, then do another and read more..

  • Page - 437

    419 chapter 13: getting the most from jquery More Functions For Manipulating HTML More Functions For Manipulating HTML You’ll often want to add, remove, and change the HTML of a page dynamically. For example, when a visitor clicks a submit button on a form, you might want the text “Send form information. Please wait.” to appear on the screen. read more..

  • Page - 438

    420 javascript & jquery: the missing manual More Functions For Manipulating HTML While you may only need the functions listed above and discussed in Chapter 4, jQuery provides other functions that provide additional ways of manipulating the HTML of a page: • .wrap() wraps each element in a selection in a pair of HTML tags. For example, what if you want to read more..

  • Page - 439

    421 chapter 13: getting the most from jquery Advanced Event Handling <div id="outer"> <div id="inner"> <p>This is the contents of outer</p> </div> </div> • .unwrap() simply removes the parent tag surrounding the selection. For ex- ample, say a page has the following HTML: <div> <p>a paragraph</p> <div> Running the code read more..

  • Page - 440

    422 javascript & jquery: the missing manual Advanced Event Handling The .bind() function receives a few arguments: the event type (‘click’, ‘m ouseover’, and so on) and a function to run when that event occurs. For example, you can re- write the code above like this: $('h1').bind('click', function() { alert('ouch!'); }); // end bind There’s one big problem with read more..

  • Page - 441

    423 chapter 13: getting the most from jquery Advanced Event Handling $('#container').delegate('selector','event',function() { //code to respond to event }); // end delegate The syntax is a little strange, so let’s break it down: • First, you start by selecting a container element. This is confusing, since with .bind() you select the elements that you want to read more..

  • Page - 442

    read more..

  • Page - 443

    425 chapter 14 Going Further with Java Script This chapter covers various concepts that can help make you a better JavaScript programmer. You don’t need most of the ideas here to write functioning Ja- vaScript programs, so don’t worry if you don’t understand them all. The first few sections provide helpful tips and methods for working with strings, read more..

  • Page - 444

    426 javascript & jquery: the missing manual Working with Strings Add a period after the name of the variable, followed by length to get the number of characters in the string: name.length. For example, assume you have a form with a text field. The field has the ID of pass- word. To make sure the password has the proper number of characters, you read more..

  • Page - 445

    427 chapter 14: going further with java script Working with Strings In this case, the conditional statement converts both the quiz-taker’s answer and the correct answer to uppercase, so ‘Greg Lemond’ becomes ‘GREG LEMOND’ and ‘Greg LeMond’ becomes ‘GREG LEMOND’. To get the string all lowercase, use the toLowerCase() method like this: var read more..

  • Page - 446

    428 javascript & jquery: the missing manual Working with Strings var quote = 'To be, or not to be.' var searchPosition = quote.indexOf('To be'); // returns 0 Here, indexOf() searches for the position of ‘To be’ inside the string ‘To be, or not to be.’ The larger string begins with ‘To be’, so indexOf() finds ‘To be’ at the first posi- read more..

  • Page - 447

    429 chapter 14: going further with java script Working with Strings The slice() method requires a number that indicates the starting index position for the extracted string (see Figure 14-2). In this example—url.slice(7)—the 7 indicates the eighth letter in the string (remember, the first letter is at position 0). The method returns all of the characters read more..

  • Page - 448

    430 javascript & jquery: the missing manual Finding Patterns in Strings Figure 14-3: The slice() method extracts a portion of a string. The actual string is not changed in any way. For instance, the string contained in the quote variable in this example isn’t changed by quote.slice(0,5). The method simply returns the extracted string, which you can store inside a read more..

  • Page - 449

    431 chapter 14: going further with java script Finding Patterns in Strings Unless you’re a super-alien from Omicron 9, there’s nothing very regular-looking about a regular expression. To create a pattern, you use characters like *, +, ?, and \w, which are translated by the JavaScript interpreter to match real characters in a string like letters, read more..

  • Page - 450

    432 javascript & jquery: the missing manual Finding Patterns in Strings However, to master regular expressions, you need to learn the often confusing sym- bols required to construct a regular expression. Building a Regular Expression While a regular expression can be made up of a word or words, more often you’ll use a combination of letters and special symbols read more..

  • Page - 451

    433 chapter 14: going further with java script Finding Patterns in Strings Character Matches | Either the characters before or after the | character. For example, a|b will match either or , but not both. (See page 440 for an example of this symbol in action.) \ Used to escape any special regex symbol (*,.,\,/, for instance) to search for a literal example of the symbol read more..

  • Page - 452

    434 javascript & jquery: the missing manual Finding Patterns in Strings 4. Put your regex into action in JavaScript. Assume you’ve already captured a user’s input into a variable named zip, and you want to test to see if the input is in the form of a valid five-number Zip code: var zipTest = /^\d\d\d\d\d$/; //create regex if (zip.search(zipTest) == -1) { read more..

  • Page - 453

    435 chapter 14: going further with java script Finding Patterns in Strings string, when what you really want is just logo.gif. To do that, use the \S charac- ter, which matches any nonspace character: \S*\.gif matches just logo.gif in the string. 4. Make the search case-insensitive. There’s one more wrinkle in this regular expression: It only finds files that read more..

  • Page - 454

    436 javascript & jquery: the missing manual Finding Patterns in Strings For example, say you want to see if a string contains either “Apr” or “April”—both of those begin with “Apr”, so you know that you want to match that, but you can’t just match “Apr”, since yo u’d also match the “Apr” in “Apricot” or “Aprimecorp.” So , read more..

  • Page - 455

    437 chapter 14: going further with java script Finding Patterns in Strings Note: For regular expressions that match the postal codes of other countries, visit http://regexlib.com/ Search.aspx?k=postal+code. That regular expression breaks down into the following smaller pieces: • \d{5} matches five digits, as in 97213. • () creates a subpattern. Everything between the parentheses read more..

  • Page - 456

    438 javascript & jquery: the missing manual Finding Patterns in Strings • \)? matches an optional closing parenthesis. • [ -.] will match either a space, hyphen, or period. (Note that normally you have to escape a period like this \. in order to tell the JavaScript interpreter that you want to match the period character and not treat it as the read more..

  • Page - 457

    439 chapter 14: going further with java script Finding Patterns in Strings Note: The email regex listed above doesn’t match all technically valid email addresses. For example, !#$%&’*+-/=?^_`.{|}~@example.com is technically a valid email address, but the regex described here won’t match it. It’s designed to find email addresses that people would actually use. If you read more..

  • Page - 458

    440 javascript & jquery: the missing manual Finding Patterns in Strings Web address Matching a web address is useful if you’re asking a visitor for his website address and you want to make sure he’s supplied one, or if you want to scan some text and identify every URL listed. A basic regular expression for URLs is: ((\bhttps?:\/\/)|(\bwww\.))\S* This read more..

  • Page - 459

    441 chapter 14: going further with java script Finding Patterns in Strings • www\. matches www.. • ) is the end of the second inner group (3 in Figure 14-4). This group will capture a URL that is missing the http:// but begins with www. • ) is the end of the outer group (1 in Figure 14-4). At this point, the regular ex- pression will match text read more..

  • Page - 460

    442 javascript & jquery: the missing manual Finding Patterns in Strings First, the code creates a variable containing a string that includes the URL www. missingmanuals.com. This variable is just for test purposes here (so you can see what the match() method does. If you actually wanted to test the contents of a text area on a form, you could use code read more..

  • Page - 461

    443 chapter 14: going further with java script Finding Patterns in Strings You could rewrite the code from page 441 using a global search, like this: // create a variable containing a string with a URL var text='there are a lot of great websites like www.missingmanuals.com and http://www.oreilly.com'; // create a regular expression with global search read more..

  • Page - 462

    444 javascript & jquery: the missing manual Finding Patterns in Strings POWER USERS’ CLINIC Using Subpatterns to Replace Text The replace() method not only can replace matched text (like the . in 10.28.2008) with another string (like /), but it can also remember subpatterns within a regular expres- sion and use those subpatterns when replacing text. As explained in the Note read more..

  • Page - 463

    445 chapter 14: going further with java script Working with Numbers Figure 14-5: This sample page, in- cluded with the tuto- rial files, lets you test out regular expres- sions using different methods—like Search or Match—and try different options such as case-insensitive or global searches. Working with Numbers Numbers are an important part of programming. They let you read more..

  • Page - 464

    446 javascript & jquery: the missing manual Working with Numbers In this example, even though the variables a and b are both strings, the JavaScript interpreter converts them to numbers to perform the multiplication (3 x 4) and re- turn the result: 12. However, when you use the + operator, the JavaScript interpreter won’t make that conversion, and you can read more..

  • Page - 465

    447 chapter 14: going further with java script Working with Numbers Note: You’re probably wondering what the 10 is doing in parseInt(age,10);. JavaScript can handle Octal numbers (which are based on 8 different digits 0-7, unlike decimal numbers which are based on 10 different digits 0-9); when you add the, 10 to parseInt(), you’re telling the JavaScript interpreter to read more..

  • Page - 466

    448 javascript & jquery: the missing manual Working with Numbers var x = '10'; // is a number if (isNaN(x)) { // won't run because x IS a number } else { // will run because x is a number } Rounding Numbers JavaScript provides a way to round a fractional number to an integer—for example, rounding 4.5 up to 5. Rounding comes in handy when you’re read more..

  • Page - 467

    449 chapter 14: going further with java script Working with Numbers var cost = 10; var printCost = '$' + cost.toFixed(2); // $10.00 The number you pass the toFixed() method determines how many decimal places to go out to. For currency, use 2 to end up with numbers like 10.00 or 9.90; if you use 3, you end up with 3 decimal places, like 10.000 read more..

  • Page - 468

    450 javascript & jquery: the missing manual Dates and Times If you want to get a random number between 1 and another number, just multiply the random() method by the uppermost number, and use the Math.ceil() method (which rounds a number up to the neareast integer). For example, if you want to simulate a die roll to get a number from 1 to read more..

  • Page - 469

    451 chapter 14: going further with java script Dates and Times The new Date() command creates a Date object containing the current date and time. Once created, you can access different pieces of time and date information using various date-related methods as listed in Table 14-3. For example, to get the current year, use the getFullYear() method like this: read more..

  • Page - 470

    452 javascript & jquery: the missing manual Dates and Times There’s no built-in JavaScript command that tells you the name of a month. For- tunately, JavaScript’s strange way of numbering months comes in handy when you want to determine the actual name of the month. You can accomplish that by first creating an array of month names, then accessing a read more..

  • Page - 471

    453 chapter 14: going further with java script Dates and Times POWER USERS’ CLINIC The Date Object Behind the Scenes JavaScript lets you access particular elements of the Date object, such as the year or the day of the month. However, the JavaScript interpreter actually thinks of a date as the number of milliseconds that have passed since midnight on January 1, 1970. read more..

  • Page - 472

    454 javascript & jquery: the missing manual Dates and Times You can use the getHours(), getMinutes(), and getSeconds() methods to get the hours, minutes, and seconds. So to display the time on a web page, add the following in the HTML where you wish the time to appear: var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = read more..

  • Page - 473

    455 chapter 14: going further with java script Dates and Times Line 8 introduces a mathematical operator called modulus and represented by a percent (%) sign. It returns the remainder of a division operation. For example, 2 divides into 5 two times (2 x 2 is 4), with 1 left over. In other words, 5 % 2 is 1. So in this case, if the hour is 18, 18 read more..

  • Page - 474

    456 javascript & jquery: the missing manual Dates and Times } time = hours; minutes = now.getMinutes(); if (minutes<10) { minutes = '0' + minutes; } time += sep + minutes; if (secs) { seconds = now.getSeconds(); if (seconds<10) { seconds read more..

  • Page - 475

    457 chapter 14: going further with java script Putting It All Together Creating a date that’s one week from today As discussed in the box on page 453, the JavaScript interpreter actually treats a date as the number of milliseconds that have elapsed since Jan 1, 1970. Another way to create a date is to pass a value representing the number of read more..

  • Page - 476

    458 javascript & jquery: the missing manual Putting It All Together jQuery plug-ins are supplied as external files, so you need to link them to a web page if you want to use them. Linking to an external JavaScript file is as easy as this: <script src="js/ui.tabs.js"></script> Putting your own JavaScript code into external JavaScript files can also read more..

  • Page - 477

    459 chapter 14: going further with java script Writing More Efficient JavaScript For example, if you have a search box at the top of the page and a separate form for submitting a product order, the code in line 3 will put the focus on the search box and not the first text field in the order form. In this case, you need to think through the read more..

  • Page - 478

    460 javascript & jquery: the missing manual Writing More Efficient JavaScript Putting Preferences in Variables One important lesson that programmers learn is how to extract details from scripts so that they are more flexible and easier to update. For example, say you want to change the color of a paragraph of text to orange when a visitor clicks on read more..

  • Page - 479

    461 chapter 14: going further with java script Writing More Efficient JavaScript 14 ); 15 }); //end ready() Now, the click and hover events use the same color—#F60 (since the tdColor variable is set to the value of pColor in line 3 of the code). However, if you later decide that you want the table cells to have a different color, read more..

  • Page - 480

    462 javascript & jquery: the missing manual Writing More Efficient JavaScript Depending upon the result of the condition, either A (if the condition is true) or B (if the condition is false) is returned. The ? precedes the true result, while the : precedes the false result. So, for example, the above code could be rewritten like this: var status=(login)?'Logged read more..

  • Page - 481

    463 chapter 14: going further with java script Writing More Efficient JavaScript Notice that there’s an awful lot of favoriteColor == ‘some value’ in that code. In fact, ‘favoriteColor ==’ appears three times in just nine lines of code. If all you’re doing is testing the value of a variable repeatedly, then the switch statement provides a more read more..

  • Page - 482

    464 javascript & jquery: the missing manual Writing More Efficient JavaScript case 37: //do something break; To test whether the variable is true or not, you’d write this: case true: //do something break; After the first line, you add the statements you want to execute if the variable match- es the test case value. Finally, you add a break; statement. read more..

  • Page - 483

    465 chapter 14: going further with java script Creating Fast- Loading JavaScript break; default: message = 'What kind of favorite color is that?'; } This is similar to using if (favoriteColor == ‘navy’ || favoriteColor == ‘blue’ || favor- iteColor == ‘indigo’) in an if/else statement. Creating Fast-Loading JavaScript Once you starting using read more..

  • Page - 484

    466 javascript & jquery: the missing manual Creating Fast- Loading JavaScript 1. Launch a web browser and visit http://www.refresh-sf.com/yui/. This is the site for the Online YUI Compressor. 2. Click the File(s) link. Alternatively, you can just copy the JavaScript code from your text editor and paste it into the large text box at the site’s homepage; you can read more..

  • Page - 485

    467 chapter 15 Troubleshooting and Debugging Everybody makes mistakes, but in JavaScript, mistakes can keep your programs from running correctly—or at all. When you first start out with JavaScript, you’ll probably make a lot of mistakes. Trying to figure out why a script isn’t behaving the way it should can be frustrating, but it’s all a part of read more..

  • Page - 486

    468 javascript & jquery: the missing manual Top JavaScript Programming Mistakes of the most common mistakes is simply forgetting to include a closing punctuation mark. For example, alert(‘hello’ ; will produce an error because the closing parenthe- sis is missing: alert(‘hello’);. Leaving off a closing parenthesis will cause a syntax error (see the box on page read more..

  • Page - 487

    469 chapter 15: troubleshooting and debugging Top JavaScript Programming Mistakes You’ll encounter a syntax error when you forget to include the second quote mark as well. For example, alert(‘hello); produces an error because the final single quote is missing: alert(‘hello’);. In Firefox, if you forget to include both quote marks, you’ll get an “unterminated string read more..

  • Page - 488

    470 javascript & jquery: the missing manual Top JavaScript Programming Mistakes Then finish the object: var options = { rules : { name : 'required', email: 'email' }, messages : { name : 'Please type your name', email: 'Please type your e-mail address.' } }; This approach lets you check your work through various steps and read more..

  • Page - 489

    471 chapter 15: troubleshooting and debugging Top JavaScript Programming Mistakes UP TO SPEED Types of Errors There are three basic categories of errors that you’ll en- counter as you program JavaScript. Some of these errors are immediately obvious, while others don’t always rear their ugly heads until the script is up and running. Syntax Errors . A syntax error is read more..

  • Page - 490

    472 javascript & jquery: the missing manual Top JavaScript Programming Mistakes Quotation Marks Quote marks often trip up beginning programmers. Quote marks are used to create strings of letters and other characters (see page 43) to use as messages on the page, or as variables in a program. JavaScript, like other programming languages, lets you use either double read more..

  • Page - 491

    473 chapter 15: troubleshooting and debugging Top JavaScript Programming Mistakes For example, the following code generates a syntax error: var if = "This won't work."; Since if is used to create conditional statements—as in if (x==0)—you can’t use it as a variable name. Some browsers, however, won’t generate an error if you use words that are part of read more..

  • Page - 492

    474 javascript & jquery: the missing manual Top JavaScript Programming Mistakes browser’s built-in alert() command, while the second ALERT(‘hi’) attempts to call a user-defined function named ALERT(). You can run into this problem if you use the long-winded DOM selection methods getElementsByTagName() or getElementById(), since they use both upper and lower- case read more..

  • Page - 493

    475 chapter 15: troubleshooting and debugging Top JavaScript Programming Mistakes paths is the location of the web page itself. So, any document-relative paths you in- clude in the JavaScript file must be relative to the web page and not the JavaScript file. Here’s a simple example to illustrate this problem. Figure 15-2 represents the struc- ture of a very read more..

  • Page - 494

    476 javascript & jquery: the missing manual Top JavaScript Programming Mistakes then, in each web page, define variables to hold document-relative paths from the current web page to the correct file. Finally, you could use an approach like the one used in the slideshow on page 222. The paths come from the web page and are embedded within links on the read more..

  • Page - 495

    477 chapter 15: troubleshooting and debugging Debugging with Firebug UP TO SPEED Programming Tips to Reduce Errors The best way to deal with errors and bugs in your programs is to try to stop them as early as possible. It can be really difficult to track down the cause of errors in a program if you wait until you’ve written a 300-line script before testing it in read more..

  • Page - 496

    478 javascript & jquery: the missing manual Debugging with Firebug 1. Visit http://addons.mozilla.org/firefox/addon/firebug using Firefox, and click the “Add to Firefox” button. To protect you from accidentally installing a malicious extension, Firefox stops your first attempt at installing the extension. A Software Installation window appears, warning you that malicious software read more..

  • Page - 497

    479 chapter 15: troubleshooting and debugging Debugging with Firebug Figure 15-3: Firebug’s console lists any JavaScript errors Firefox has encoun- tered on the current page. To see the exact line of code on which the error was encountered, click the code snippet under the error (circled). Firebug then switches from the console tab to the script tab and highlights the line read more..

  • Page - 498

    480 javascript & jquery: the missing manual Debugging with Firebug Firebug provides a better way to look into your program. The Firebug console not only lists errors (see previous section), but can also be used to output messages from the program. The console.log() function works similar to the document.write() func- tion (page 31), but instead of printing read more..

  • Page - 499

    481 chapter 15: troubleshooting and debugging Debugging with Firebug Tutorial: Using the Firebug Console In this tutorial, you’ll learn how to use the console.log() function to see what’s going on inside your program. You’ll create a script that displays the number of characters typed into a text box on a form. Note: See the note on page 29 for read more..

  • Page - 500

    482 javascript & jquery: the missing manual Debugging with Firebug The word READY should appear in the console (circled in Figure 15-4). The script you’re creating will display the number of characters typed into a form’s text field each time your visitor types a character. To accomplish this, you’ll add a keyup event (page 162) to that text box. read more..

  • Page - 501

    483 chapter 15: troubleshooting and debugging Debugging with Firebug Save the page; reload it in Firefox and type a few characters into the text box. Make sure Firebug’s console is open, and you should see several lines (one for each character you typed) of ‘Event: keyup’, Now that the keyup event is work- ing, you might want to retrieve the read more..

  • Page - 502

    484 javascript & jquery: the missing manual Debugging with Firebug 5 console.log('Event: keyup'); 6 var text = $(this).val(); 7 console.log('Contents of comments: %s',text); 8 var chars = text.length; 9 console.log('Number of characters: %d',chars); 10 $('#count').text(chars + " characters"); 11 read more..

  • Page - 503

    485 chapter 15: troubleshooting and debugging Debugging with Firebug More Powerful Debugging The Firebug console is a great way to print out messages so you can see what’s going on when a program runs. But sometimes a program zips by so quickly it’s hard to see what’s going on during each step. You need a way to slow things down. Fortunately, read more..

  • Page - 504

    486 javascript & jquery: the missing manual Debugging with Firebug Figure 15-6: The Firebug debugger lets you set breakpoints (lines where the script stops and waits), control the execution of the script, and watch vari- ables in the Watch list. As the debugger executes the script, the current line (the one that’s about to run) has a yellow arrow to its left (circled). read more..

  • Page - 505

    487 chapter 15: troubleshooting and debugging Debugging with Firebug After the script begins to run, as soon as a breakpoint is reached, the script stops. The program is frozen in time, waiting to execute the line from the first breakpoint. 7. Use Firebug’s controls to step through the execution of the program. Firebug provides four controls (see Figure 15-6) read more..

  • Page - 506

    488 javascript & jquery: the missing manual Debugging with Firebug includes a call to a function, it won’t enter the function—it steps over the func- tion and stops at the next line of code. This option is great if you know the function that’s being called works flawlessly. For example, if your script calls a jQuery function, you’ll want to step read more..

  • Page - 507

    489 chapter 15: troubleshooting and debugging Debugging Tutorial Figure 15-7: Firebug’s Watch list shows the value of differ- ent variables as the program runs. You can add your own expressions to the list, which ap- pear as grey stripes at the top of the window. Add new expression You can add your own variables and expressions using the yellow bar with the label read more..

  • Page - 508

    490 javascript & jquery: the missing manual Debugging Tutorial Note: See the note on page 29 for information on how to download the tutorial files. To complete this tutorial, you’ll need run the Firefox web browser and have the Fire- bug extension installed and turned on—see page 477 for instructions. 1. Start Firefox and open the file debugger.html from the read more..

  • Page - 509

    491 chapter 15: troubleshooting and debugging Debugging Tutorial 3. Launch your text editor and open the file debugger.html. Locate line 15 (it’s a single ; on a line by itself). Type a closing square bracket before the ; so the line looks like this: ]; This bracket ended a nested array (page 110) that contained all of the questions and answers for read more..

  • Page - 510

    492 javascript & jquery: the missing manual Debugging Tutorial 8. Return to your text editor, and then remove the last s from askQuestions() in line 70 (near the end of the script). Save the file, reload it in Firefox, and then click the Start Quiz button again. Now, a quiz question appears along with five multiple-choice options. Unfortu- nately, the last read more..

  • Page - 511

    493 chapter 15: troubleshooting and debugging Debugging Tutorial A red dot appears to the left of line 46. The dot indicates a breakpoint, or a spot in the code, where the JavaScript interpreter stops running the script. In other words, when this script runs again, the moment the JavaScript interpreter hits that line, it stops, and you’ll be able to read more..

  • Page - 512

    494 javascript & jquery: the missing manual Debugging Tutorial Figure 15-10: When you step through a pro- gram using Firebug, red circles to the right of a line number indicate a break point, while yellow arrows indicate the line of code that the JavaScript interpreter is currently stopped at. Click Step Over (or Step Into) to run that line of code and stop at the read more..

  • Page - 513

    495 chapter 15: troubleshooting and debugging Debugging Tutorial 16. Return to your text editor, and change the for loop at line 46 to read: for (i=0;i<answers.length;i++) { Now the loop only runs for the number of items in the answers array, creating one radio button for each possible answer. 17. Save the file, and preview it in Firefox. You can turn read more..

  • Page - 514

    read more..

  • Page - 515

    497 appendix a JavaScript Resources This book provides enough information and real-world techniques to get your JavaScript career off to a great start. But no one book can answer all of your JavaScript or jQuery questions. There’s plenty to learn when it comes to Ja- vaScript programming, and this appendix gives you taking-off points for further research and read more..

  • Page - 516

    498 javascript & jquery: the missing manual Basic JavaScript • MSDN JavaScript Language Reference (http://msdn.microsoft.com/en-us/ library/yek4tbz0(v=VS.94).aspx) from Microsoft is an excellent resource if you’re developing with Internet Explorer. While it provides technical informa- tion on the JavaScript used in other browsers, this resources provides a lot of IE-only read more..

  • Page - 517

    499 appendix a: javascript resources jQuery jQuery Much of this book covered the jQuery JavaScript library, but there’s still lots to learn about this powerful, timesaving, and fun programming library. Articles and Presentations • jQuery Essentials by Marc Grabanski (www.slideshare.net/1Marc/jquery- essentials) is a fun and thorough slideshow covering the basics of read more..

  • Page - 518

    500 javascript & jquery: the missing manual Ajax • jQuery: Novice to Ninja by Earle Casteldine and Craig Sharkie (Sitepoint) pro- vides lots of instructions in using jQuery as many hands-on examples that show how to tackle common user-interface needs. Ajax Ajax brings together your Web browser, JavaScript, and server-side programming, for triple the fun (and three read more..

  • Page - 519

    501 appendix a: javascript resources CSS Websites • Eloquent JavaScript (http://eloquentjavascript.net) is a JavaScript tutorial site. It’s organized well, with creative ways of teaching lessons. Although it’s sup- posed to be a beginner JavaScript tutorial site, the author writes as though he’s talking to a bunch of computer scientists, so it’s not read more..

  • Page - 520

    502 javascript & jquery: the missing manual CSS Websites • The Complete CSS Guide from WestCiv (www.westciv.com/style_master/ academy/css_tutorial) covers pretty much every part of Cascading Style Sheets. You won’t learn a lot of different techniques here, but the basics of what CSS is and how to create styles and style sheets are thoroughly covered. • The read more..

  • Page - 521

    503 index Index - (minus sign) subtraction operator, 50 -- subtract 1 operator, 54 -= subtract and assign operator, 54 (...) (parentheses) following function name, 42, 100, 102 grouping operations, 51 in if statement, 79 syntax errors involving, 468 . (period) preceding class selectors, 132 preceding jQuery functions, 138 preceding object properties or read more..

  • Page - 522

    504 index Index addClass() function, jQuery, 142 addition operator (+), 50 adjacent sibling selectors, 133 after() function, jQuery, 139–140, 419 Ajax (Asynchronous JavaScript and XML), 23, 341–349 error handling, 364 JavaScript for, 345 jQuery functions for error() function, 364 get() function, 356–357, 358, 365–370 getJSON() function, 371–376, 378, 381 read more..

  • Page - 523

    Index 505 index bind() function, jQuery, 177–179, 421–422 blur event, 161, 266 blur() function, jQuery, 266 blur() method, window object, 244 body tag, HTML, 6 books and publications CSS: The Definitive Guide (O’Reilly), 502 CSS: The Missing Manual 2nd Edition (O’Reilly), 4, 132, 502 Head First HTML with CSS and XHTML (O’Reilly), 4 Head First read more..

  • Page - 524

    Index 506 index concatenation operator (+), 51 condition in do/while loop, 98 in for loop, 97 in if statement, 79–81 combining, 86–88 negating, 87–88 setting variables based on, 461–462 in while loop, 93–95 conditional statements, 77–89 conditions in, 79–81 combining, 86–88 negating, 87–88 else clause in, 82–83 else if statement, 83–85 if read more..

  • Page - 525

    Index 507 index dimensions of browser window, 319–320 of content slider, 316–317 of document, 320 of web page elements, 319–322 disabling form fields, 269–271, 273–276 divide and assign operator (/=), 54 division operator (/), 50 div tag, HTML for tabbed panels, 302, 303–304 for tooltips, 326–327 doctype declaration, HTML, 5 document read more..

  • Page - 526

    Index 508 index examples. See online resources; tutorials exclamation point (!) NOT operator, 87–88 != inequality operator, 80–81 !== strict inequality operator, 80 Expression Web Designer, 11 external HTML files, loading into web page, 349–356 external JavaScript files, 27–29, 457–459 attaching to web pages, 27–29, 33–34 compressing, 465–466 read more..

  • Page - 527

    Index 509 index validating, 278–291 error messages for, 283–284, 288–291, 299–300 plug-in for, setting up, 280–281 on server, 289 tutorial for, 291–300 validation rules for, 281–283, 284–288 form tag, HTML, 257–259 forward slash (/) division operator, 50 in HTML tags, 6 /= divide and assign operator, 54 /*...*/ enclosing comments, 73 /.../ read more..

  • Page - 528

    Index 510 index HTML (Hypertext Markup Language), 4–7. See also web pages; specific tags effects for. See effects, jQuery loading in web page from external file, 349– 352 manipulating, 124–127, 138–141, 146–147, 419–421 model of, for a web page. See DOM rendered, viewing source for, 141 selecting tags in with JavaScript, 128–129 with read more..

  • Page - 529

    Index 511 index post() function, 356–357, 358 serialize() function, 360 animations, 192–198 attaching to a web page, 122–124 CSS classes, manipulating, 142–143 CSS properties, manipulating, 143–146 DOM, traversing, 413–418 downloading, 120–121 effects. See effects events. See events filters, 135–136, 260–261 forms. See forms functions. See also read more..

  • Page - 530

    Index 512 index li tag, HTML, for navigation menu, 250–252 load event, 160 load() function, jQuery, 349–356 local variables, 107–108 location property, windows, 243 logging in without leaving web page, 343 logical AND operator (&&), 86 logical OR operator (||), 86 logic errors, 471 login slider tutorial, 190–192 loops, 93–99 automatic, for read more..

  • Page - 531

    Index 513 index examples using, 2, 23, 124 libraries for, 119 jQuery, 12, 499 documentation for, 407–413 examples using, 4 performance of, 407 plug-ins for, 256 UI project, 312 PHP, 351 open() method, window object, 240–241 order of operations, 51 OR operator, logical (||), 86 outerHeight() function, jQuery, 321 outerWidth() function, jQuery, 321 read more..

  • Page - 532

    Index 514 index preventDefault() function, jQuery, 175, 237–238 prev() function, 417 processContacts() function, jQuery, 372 programming, 22–25 prompt() function, JavaScript, 57–58 properties, CSS, 9 hyphens in, handling in JavaScript, 193 manipulating, 143–146 properties, JavaScript, 71 Prototype library, 119 p tag, HTML, 6, 7 pull quotes, tutorial for, read more..

  • Page - 533

    Index 515 index searching selections, 365, 407, 413, 414–415 searching strings for exact strings, 427–428 for patterns. See patterns in strings search() method, strings, 431 :selected filter, 261 selectors, 8, 129–138 acting on each element of, 147–150 adjacent sibling selectors, 133 assigning events to, 163–164 attribute selectors, 133–134, 239 read more..

  • Page - 534

    Index 516 index submit event, 161, 263–264 submit() function, jQuery, 263–264, 271 :submit selector, 260 submitting forms, 161, 263–264 multiple times, preventing, 271 without reloading page, 343, 347–348, 365–370 subpatterns, in regular expressions, 437, 438, 444 subtract 1 operator (--), 54 subtract and assign operator (-=), 54 subtraction operator read more..

  • Page - 535

    Index 517 index typeof operator, 72 typing errors. See syntax errors U ul tag, HTML, 7 for navigation menu, 250–252 for tabs in tabbed panels, 302–303, 304 unbind() function, jQuery, 175–176 Uniform Resource Locator. See URL unload event, 160 Unobtrusive JavaScript (web site), 501 unshift() method, arrays, 64, 65 unwrap() function, 421 URL read more..

  • Page - 536

    Index 518 index window object (browser window), 72. See also dialog boxes closing, 243 events for, 160 focus of, setting, 244 methods for, 240–241, 243–245. See also built-in functions moving, 244 new creating, 240–245 creating within an iframe, 245–249 opening external links in, 238–240 properties of, 241–243 resizing, 244 scrolling, 244 wrap() read more..

  • Page - 537

    Colophon This book was composited in Adobe InDesign CS4 by Newgen North America. Rebecca Demarest provided production assistance. The cover of this book is based on a series design originally created by David Freed- man and modified by Mike Kohnke, Karen Montgomery, and Fitch (www.fitch .com). Back cover design, dog illustration, and color selection by Fitch. David read more..

  • Page - 538

    D own loa d from Wow! eBoo k <www.wowe boo k.com> read more..

Write Your Review