Javascript & Jquery Missing Manual

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Shortcuts for performing math on a variable

+= / score += 10 / score = score + 10 -= / score -= 10 / score = score - 10 *= / score *= 10 / score = score * 10 /= / score /= 10 / score = score / 10 ++ / score++ / score = score + 1 -- / score-- / score = score - 1

Various ways of adding elements to an array

.lengthproperty / var p = [0,1,2,3] / p[p.length]=4 / [0,1,2,3,4] push() / var p = [0,1,2,3] / p.push(4,5,6) / [0,1,2,3,4,5,6] unshift() / var p = [0,1,2,3] / p.unshift(4,5) / [4,5,0,1,2,3]

Acting on Each Element in a Selection

1. Retrieving all links that point outside your site. 2. Getting the HREF attribute of each link (the URL). 3. Adding that URL to the other list of links in the bibliography box. jQuery doesn't have a built-in function that performs these exact steps, but you can use the each() function to do it yourself. It's just a jQuery function, so you slap it on at the end of a selection of jQuery elements like this: $('selector').each();

Using Events the jQuery Way 2. Assign an event.

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 parentheses. To add a click event to an element with an ID of menu, you'd write this: $('#menu').click();

Use these comparison operators to test values as part of a conditional statement 1

== / Equal to. Compares two values to see if they're the same. Can be used to compare numbers or strings. != / Not equal to. Compares two values to see if they're not the same. Can be used to compare numbers or strings. === / Strict equal to. Compares not only the values but also the type of the value. In other words, the two values must also share the same type—string, number, or Boolean—in order for the condition to be true. For example, while '2' == 2 is true, '2' === 2 is not true, because the first value is inside quote marks (a string) and the second is a number. Many programmers prefer this strict equality operator because it ensures you're comparing like types of information. However, when retrieving a number value from a form (or a prompt() dialog box), you'll get a string value like '2', and not an actual number. You should convert the string to a number before comparing using a comparison. !== / Strict not equal to. Like strict equal to compare values and type. For example, while '2' != 2 is false, '2' ! = = 2 is true, because although the values are the same, the types are not.

CSS components: Property

CSS offers a wide range of formatting options, called properties. A property is a word—or a few hyphenated words—indicating a certain style effect. Most properties have straightforward names like font-size, margin-top, and background-color.

Use these comparison operators to test values as part of a conditional statement 2

> / Greater than. Compares two numbers and checks if the number on the left side is greater than the number on the right. For example, 2 > 1 is true, since 2 is a bigger number than 1, but 2 > 3 is false, because 2 isn't bigger than 3. < / Less than. Compares two numbers and checks if the number on the left side is less than the number on the right. For example, 2 < 3 is true, because 2 is a smaller number than 3, but 2 < 1 is false, because 2 isn't less than 1. >= / Greater than or equal to. Compares two numbers and checks if the number on the left side is greater than or the same value as the number on the right. For example, 2 >= 2 is true, because 2 is the same as 2, but 2 >= 3 is false, because 2 isn't a bigger number 3, nor is it equal to 3. <= / Less than or equal to. Compares two numbers and checks if the number on the left side is less than or the same value as the number on the right. For example, 2 <= 2 is true, because 2 is the same as 2, but 2 <= 1 is false, because 2 isn't a smaller number than 1, nor is 2 equal to 1.

About JavaScript Libraries

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 collection of prewritten JavaScript functions that you add to your web page. These functions make it easy to complete common tasks. Often, you can replace many lines of your own JavaScript programming (and the hours required to test them) with a single function from a JavaScript library. There are lots of JavaScript libraries out there, and many of them help create major websites like Yahoo!, Amazon, CNN, Apple, and Twitter. jQuery lets other programmers create plugins—add-on JavaScript programs that work in conjunction with jQuery to make certain tasks, effects, or features incredibly easy to add to a web page. Plug-ins that make validating forms, adding drop-down navigation menus, and building interactive slideshows a half-hour's worth of work, instead of a two-week project.

Statements

A JavaScript statement is a basic programming unit, usually representing a single step in a JavaScript program. Think of a statement as a sentence: Just as you string sentences together to create a paragraph (or a chapter, or a book), you combine statements to create a JavaScript program. In the previous chapter, you saw several examples of statements. For example: alert('Hello world!'); Each statement ends with a semicolon—it's like a period at the end of a sentence. The semicolon makes it clear that the step is over and that the JavaScript interpreter should move on to the next action.

Functions: Turn Useful Code Into Reusable Commands

A function is a series of programming steps that you set up at the beginning of your script—the equivalent of providing detailed directions to your assistant. Those steps aren't actually run when you create the function; instead, they're stored in the web browser's memory, where you can call upon them whenever you need those steps performed. The keyword function lets the JavaScript interpreter know you're creating a function—it's similar to how you use if to begin an if/else statement or var to create a variable. Next, you provide a function name; as with a variable, you get to choose your own function name. Follow the same rules listed on page 30 for naming variables. In addition, it's common to include a verb in a function name like calculateTax, getScreenHeight, updatePage, or fadeImage. An active name makes it clear that it does something and makes it easier to distinguish between function and variable names. function printToday() { var today = new Date(); document.write(today.toDateString()); } The function's name is printToday. It has just two lines of JavaScript code that retrieve the current date, convert the date to a format we can understand (that's the toDateString() part), and then print the results to the page using our old friend the document.write() command. But how do you run a function? In programming-speak, you call the function whenever you want the function to perform its task. Calling the function is just a matter of writing the function's name, followed by a pair of parentheses. For example, to make our printToday function run, you'd simply type: printToday();

Form Events - reset

Although not as common as they used to be, a Reset button lets you undo any changes you've made to a form. It returns a form to the state it was when the page was loaded. You can run a script when the visitor tries to reset the form by using the reset event. For example, if the visitor has made some changes to the form, you might want to pop up a dialog box that asks "Are you sure you want to delete your changes?" The dialog box could give the visitor a chance to click a No button and prevent the process of resetting (erasing) the form

Compiled vs. SCRIPTING Languages

A scripting language, on the other hand, is only compiled when an interpreter (another program that can convert the script into something a computer can understand) reads it. In the case of JavaScript, the interpreter is built into the web browser. So when your web browser reads a web page with a JavaScript program in it, the web browser translates the JavaScript into something the computer understands. As a result, a scripting language operates more slowly than a compiled language, because every time it runs, the program must be translated for the computer. Scripting languages are great for web developers: Scripts are generally much smaller and less complex than desktop programs, so the lack of speed isn't as important. In addition, because they don't require compiling, creating and testing programs that use a scripting language is a much faster process.

Variables

A variable is a way to store information so you can later use and manipulate it. For example, imagine a JavaScript-based pinball game where the goal is to get the highest score. When a player first starts the game, her score will be 0, but as she knocks the pinball into targets, the score will get bigger. In this case, the score is a variable because it starts at 0 but changes as the game progresses—in other words, a variable holds information that can change with the circumstances. Think of a variable as a kind of basket: You can put an item into a basket, look inside the basket, dump out the contents of a basket, or even replace what's inside the basket with something else. However, even though you might change what's inside the basket, the basket itself remains the same.

Handling Repetitive Tasks with Loops - While Loops

A while loop repeats a chunk of code as long as a particular condition is true; in other words, while the condition is true. The basic structure of a while loop is this: while (condition) { // javascript to repeat } Unlike a conditional statement, when the JavaScript interpreter reaches the closing brace of a while statement, instead of continuing to the next line of the program, it jumps back to the top of the while statement and tests the condition a second time. If the condition is again true, the interpreter runs the JavaScript between the braces a second time. This process continues until the condition is no longer true; then the program continues to the next statement following the loop.

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 fires, as programmers put it. Web browsers actually fire several events whenever you click the mouse button. First, as soon as you press the mouse button, the mousedown event fires; then, when you let go of the button, the mouseup event fires; and finally, the click event fires

Adding a Backup Plan

An if statement has its own kind of backup plan, called an else clause. For example, say as part of the JavaScript testing script, you want to notify the test taker if he gets the answer right, or if he gets it wrong. Here's how you can do that: 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. If the number 31 is stored in the variable answer, then the "correct" alert appears; otherwise, the "wrong" alert appears.

Advanced Event Management

As jQuery has evolved, the names used to add and remove events to elements have changed quite a bit. If you're reading older books or blog posts, you might run into function names like bind(), live(), and delegate(). Those have all been replaced with the on() function to add events to elements. In addition, the off() function replaces the older unbind() function for removing events from elements. The basic format of the on() function is the following: $('#selector').on('click', selector, myData, functionName); The first argument is a string containing the name of the event. If you do supply the second argument, it must be a valid selector like tr, .callout, or #alarm. The third argument is the data you wish to pass to the function - either an object literal or a variable containing an object literal. The fourth argument passed to the on() function is another function—the one that does something when the event is triggered.

Removing Events

At times, you might want to remove an event that you had previously assigned to tag. jQuery's off() function lets you do just that. To use it, first create a jQuery object with the element you wish to remove the event from. Then add the off() function, it a string with the event name. For example, if you want to prevent all tags with the class tabButton from responding to any click events, you can write this: $('a').mouseover(function() { alert('You moved the mouse over me!'); }); $('#disable').click(function() { $('a').off('mouseover'); }); If you want to remove all events from an element, don't give the off() function any arguments. For example, to remove all events—mouseover, click, dblclick, and so on—from a submit button, you could write this code: $('input[type="submit"]').off(); This is a pretty heavy-handed approach, however, and in most cases you won't want to remove all event handlers from an element.

Mousing Over and Off an Element

Because coupling these two events is so common, jQuery provides a shortcut way of referring to both. jQuery's hover() function works just like any other event, except that instead of taking one function as an argument, it accepts two functions. The first function runs when the mouse travels over the element, and the second function runs when the mouse moves off the element. The basic structure looks like this: $('#selector').hover(function1, function2); You'll frequently see the hover() function used with two anonymous functions. That kind of code can look a little weird; the following example will make it clearer. Suppose when someone mouses over a link with an ID of menu, you want a (currently invisible) DIV with an ID of submenu to appear. Moving the mouse off of the link hides the submenu again. You can use hover() to do that: $('#menu').hover(function() { $('#submenu').show(); }, function() { $('#submenu').hide(); }); // end hover

Understanding jQuery Selections - AUTOMATIC LOOPS

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 example, to select all images inside a <div> tag with an ID of slideshow and then hide those images, you write this in jQuery: $('#slideshow img').hide(); The list of elements created with $('#slideshow img') might include 50 images. The hide() function automatically loops through the list, hiding each image individually.

CSS components: Declaration

Between the opening and closing braces of a declaration, you add one or more declarations, or formatting instructions. Every declaration has two parts, a property and a value, and ends with a semicolon. A colon separates the property name from its value: color : red;.

Understanding jQuery Selections - CHAINING FUNCTIONS

Chaining jQuery functions lets you concisely carry out a large number of actions. For example, say you not only want to set the width and height of the <div> tag, but also want to add text inside the <div> and make it fade into view (assuming it's not currently visible on the page). You can do so very succinctly like this: $('#popUp').width(300).height(300).text('Hi!').fadeIn(1000); The ability to chain functions is built into jQuery. Chaining is not a regular part of JavaScript, so you can't just add non-jQuery functions (either ones you create or built-in JavaScript functions) in the chain, without some specific programming on your part.

Combining Strings

Combining strings is called concatenation, and you accomplish it with the + operator. Yes, that's the same + operator you use to add number values, but with strings it behaves a little differently. Here's an example: var firstName = 'John'; var lastName = 'Smith'; var fullName = firstName + lastName; In this example, the resulting string is "JohnSmith"—there isn't a space between the two names, as concatenating just fuses the strings together. In this case (and many others), you need to add an empty space between strings that you intend to combine: var fullName = firstName + ' ' + lastName;

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 an if/then conditional statement looks like this: if (score > 100) { alert('You won!'); } There are three parts to the statement: if indicates that the programming that follows is a conditional statement; the parentheses enclose the yes or no question, called the condition (more on that in a moment); and the curly braces ({ }) mark the beginning and end of the JavaScript code that should execute if the condition is true. The important part is score > 100. That phrase is the condition, and it simply tests whether the value stored in the score variable is greater than 100. If it is, then a "You won!" dialog box appears; if the player's score is less than or equal to 100, then the JavaScript interpreter skips the alert and moves onto the next part of the program.

Getting jQuery

Content distribution network—that is, another website hosts the jQuery file and sends it out to anyone who requests it. There are a couple of benefits to this approach: First, you can save your web server a few milliseconds by letting Google, Microsoft, or jQuery handle distributing the file to your site's visitors. In addition, CDNs have the added benefit of having servers located around the globe. So if someone in Singapore, for example, visits your site, he'll receive the jQuery file from a server that's probably a lot closer to him than your web server, which means he'll get the file faster and your site will appear to run more quickly. Lastly, and most importantly, because other designers use these CDNs as well, there's a pretty good chance that someone visiting your site already has the jQuery file saved in their browser's cache.

CSS components: Value

Finally, you get to express your creative genius by assigning a value to a CSS property—by making a background blue, red, purple, or chartreuse, for example. Different CSS properties require specific types of values—a color (like red, or #FF0000), a length (like 18px, 2in, or 5em), a URL (like images/ background.gif), or a specific keyword (like top, center, or bottom).

Using Events the jQuery Way 3. Pass a function to the event.

Finally, you need to define what happens when the event fires. To do so, you pass a function to the event. The function contains the commands that will run when the event fires: for example, making a hidden <div> tag visible or highlighting a moused-over element. You can pass a previously defined function's name like this: $('#start').click(startSlideShow); However, the most common way to add a function to an event is to pass an anonymous function to the event.

Adding Content to a Page .html()

Here are the five most useful jQuery functions for manipulating content on a page: • .html() can both read the current HTML inside an element and replace the current contents with some other HTML. You use the html() function in conjunction with a jQuery selection. To retrieve the HTML currently inside the selection, just add .html() after the jQuery selection. For example, you can run the following command using the HTML snippet at the beginning of this section: alert($('#errors').html()); If you supply a string as an argument to .html(), you replace the current contents inside the selection: $('#errors').html('<p>There are four errors in this form</p>'); This line of code replaces all of the HTML inside an element with an ID of errors.It would change the example HTML snippet to: <div id="container"> <div id="errors"> <p>There are four errors in this form</p> </div> </div>

Changing the Values in Variables

If you just want to replace what's contained inside a variable, assign a new value to the variable. For example: var score = 0; score = 100; To add to the value of a variable, you use the variable's name as part of the operation, like this: score = score + 100;

The Order of Operations

If you perform several mathematical operations at once—for example, if you add up several numbers and then multiply them all by 10—you need to keep in mind the order in which the JavaScript interpreter performs its calculations. Some operators take precedence over other operators, so they're calculated first. This fact can cause some unwanted results if you're not careful. Take this example: 4 + 5 * 10 You might think this is simply calculated from left to right: 4 + 5 is 9 and 9 * 10 is 90. It's not. The multiplication actually goes first, so this equation works out to 5 * 10 is 50, plus 4 is 54. Multiplication (the * symbol) and division (the / symbol) take precedence over addition (+) and subtraction (-). To make sure that the math works out the way you want it, use parentheses to group operations. For example, you could rewrite the equation above like this: (4 + 5) * 10 Any math that's performed inside parentheses happens first, so in this case the 4 is added to 5 first and the result, 9, is then multiplied by 10.

ADDING AN ITEM TO THE BEGINNING OF AN ARRAY

If you want to add an item to the beginning of an array, use the unshift() command.Here's an example of adding the bold value to the beginning of the properties array: var properties = ['red', '14px', 'Arial']; properties.unshift('bold'); or properties.unshift('bold', 'italic', 'underlined');

Creating a Variable

In JavaScript, to create a variable named score, you would type: var score; Variable names must begin with and contain a letter, $, or _. Variable names are case-sensitive. 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 for a variable used to track a player's game score.

For Loops

In a nutshell, the parts are: initialize a counter, test a condition, and change the counter. The first part (var num=1;) initializes a counter variable. This step only happens once at the very beginning of the statement. The second part is the condition, which is tested to see if the loop is run; the third part is an action that happens at the end of each loop—it usually changes the value of the counter, so the test condition eventually turns out to be false and the loop ends. Seasoned programmers often use a very short name for counter variables in for loops. In the code above, the letter i acts as the name of the counter. A one-letter name (i, j, and z are common) is fast to type; and because the variable isn't used for anything except running the loop, there's no need to provide a more descriptive name like counter. For example, say you want to print the items in an array in reverse order (in other words, the last item in the array prints first). You can do this: var example = ['first','second','third','last']; for (var j = example.length - 1 ; j >= 0; j--) { document.write(example[j] + '<br>'); }

Creating a Queue

In programming circles, this concept is called FIFO for "First In, First Out." You can simulate this arrangement using arrays and the push() and shift() commands. For example, say you had an array named playlist. To add a new song to the end of the list, you'd use push(), like this: playlist.push('Yellow Submarine'); To get the song that's supposed to play next, you get the first item in the list like this: nowPlaying = playlist.shift(); This code removes the first item from the array and stores it in a variable named nowPlaying. The FIFO concept is useful for creating and managing queues such as a playlist, a to-do list, or a slideshow.

Do/While Loops

In this type of loop, the conditional test happens at the end, after the loop has run. As a result, the JavaScript code within the curly braces always run at least once. Even if the condition isn't ever true, the test isn't performed until after the code runs once.

Adding Content to a Page .before() and .after()

It's common practice to check a text field in a form to make sure that the field isn't empty when your visitor submits the form. Assume that the HTML for the field looks like the following before the form is submitted: <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, you can use the .after() function like this: $('#userName').after('<span class="error">User name required</span>'); That line of code makes the web page show the error message, and the HTML component would look like this: <input type="text" name="userName" id="userName"> <span class="error">User name required</span>

Giving Information to Your Functions

JavaScript functions can also accept information, called parameters, which the function uses to carry out its actions. For example, if you want to create a function that calculates the total cost of a person's shopping cart, then the function needs to know how much each item costs, and how many of each item was ordered. To start, when you create the function, place the name of a new variable inside the parentheses—this is the parameter. The basic structure looks like this: function functionName(parameter) { // the JavaScript you want to run } Say you want to save a few keystrokes each time you print something to a web page. You create a simple function that lets you replace the web browser's document.write() function with a shorter name: function print(message) { document.write(message); } 1. The function is read by the JavaScript interpreter and stored in memory. This step just prepares the web browser to run the function later. 2. The function is called and information—"Hello world."—is passed to the function. 3. The information passed to the function is stored in a new variable named message. This step is equivalent to var message = 'Hello world.';. 4. Finally, the function runs, printing the value stored in the variable message to the web page. 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 to wrap around the message. This way, you can print the message as a headline or a paragraph. Here's what the new function would look like: function print(message,tag) { document.write('<' + tag + '>' + message +'</' + tag + '>'); The function call would look like this: print('Hello world.', 'p');

Testing More Than One Condition

JavaScript lets you perform 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; and finally, you use the else clause as the fallback position. Here's the basic structure in JavaScript: if (condition) { // door #1 } else if (condition2) { // door #2 } else { // door #3 }

A Quick Object Lesson

Like real-world objects, JavaScript objects are also made up of different parts. In programming-speak, the parts of an object are called properties. The actions an object can perform are called methods, which are functions (like the built-in alert() function) that are specific to an object. To access an object's property or execute one of its methods, you use dot syntax—those periods! The dot (period) connects the object with its property or method. For example, document.write() means "run the write() method of the document object." If the real world worked like that, you'd have a dog wag his tail like this: dog.tail.wag(). When you create an object (also called creating an instance of that object), you can access all of the properties and methods for that object.

Form Events - change

Many form fields fire a change event when their status changes: for instance, when someone clicks a radio button, or makes a selection from a drop-down menu. You can use this event to immediately check the selection made in a menu, or which radio button was selected.

Combining Numbers and Strings pt1

Most of the mathematical operators only make sense for numbers. For example, it doesn't make any sense to multiply 2 and the string "eggs". If you try this example, you'll end up with a special JavaScript value NaN, which stands for "not a number." For example, say you want to present a message on a web page that specifies how many times a visitor has been to your website. In this case, you use the + operator to do two things: convert the number to a string and concatenate it with the other string. var message = 'You have visited this site ' + numOfVisits + ' times.'; Whenever you use the + operator with a string value and a number, the JavaScript interpreter converts the number to a string. That feature, known as automatic type conversion, can cause problems, however. var numOfShoes = '2'; var numOfSocks = 4; var totalItems = numOfShoes + numOfSocks;

COMPILED vs. Scripting Languages

Most of the programs running on your computer are written using languages that are compiled. Compiling is the process of creating a file that will run on a computer by translating the code a programmer writes into instructions that a computer can understand. Once a program is compiled, you can run it on your computer, and because a compiled program has been converted directly to instructions a computer understands, it will run faster than a program written with a scripting language. Unfortunately, compiling a program is a time-consuming process: You have to write the program, compile it, and then test it. If the program doesn't work, you have to go through the whole process again.

Using Variables

Once you declare a variable, you can store any type of data you'd like in it. To do so, you use the = sign. For example, to store the number 0 in a variable named score, you could type this code: var score; score = 0; To save typing, you can declare multiple variables with a single var keyword, like this: var x, y, z; You can even declare and store values into multiple variables in one JavaScript statement: var isSuperHero=true, isAfraidOfHeights=false; Once you've stored a value in a variable, you can access that value simply by using the variable's name. For example, to open an alert dialog box and display the value stored in the variable score, you'd type this: alert(score); Notice that you don't use quotes with a variable—that's just for strings; so the code alert('score') will display the word "score" and not the value stored in the variable score. Now you can see why strings have to be enclosed in quote marks: The JavaScript interpreter treats words without quotes as either special JavaScript objects (like the alert() command) or as variable names.

Adding jQuery to a Page

Once you've attached the jQuery file, you're ready to add your own scripts that take advantage of jQuery's advanced functions. The next step is to add a second set of <script> tags with a little bit of jQuery programming in it: <script src="js/jquery-1.11.0.min.js"></script> <script> $(document).ready(function() { // your programming goes here }); </script> The second set of <script> tags holds any programming you want to add to the particular web page; however, you're probably wondering what that $(document). ready() business is all about. The $(document).ready() function is a built-in jQuery function that waits until the HTML for a page loads before it runs your script. Why would you want to do that? Because a lot of JavaScript programming is about manipulating the contents of a web page: for example, animating a div, fading an image into view, making a menu drop down when a visitor moves over a link, and so on. To do something fun and interactive with a page element, JavaScript needs to select it. However, JavaScript can't select an HTML tag until the web browser downloads it. A web browser immediately runs any JavaScript it encounters, so the rest of the page doesn't download immediately.

Keeping Variables from Colliding

One potential problem arises when you just plop a function down into an already-created script, however. What happens if the script uses the same variable names as the function? Will the function overwrite the variable from the script, or vice versa? For example: var message = 'Outside the function'; function warning(message) { alert(message); } warning('Inside the function'); // 'Inside the function' alert(message); // 'Outside the function' Notice that the variable message appears both outside the function (the first line of the script) and as a parameter in the function. A parameter is really just a variable that's filled with data when the function's called. In this case, the function call—warning('Inside the function');—passes a string to the function and the function stores that string in the variable message. It looks like there are now two versions of the variable message. So what happens to the value in the original message variable that's created in the first line of the script? You might think that the original value stored in message is overwritten with a new value, the string 'Outside the function'; it's not. When you run this script, you'll see two alert dialog boxes: The first will say "Inside the function" and the second "Outside the function." There are actually two variables named message, but they exist in separate places.

More Complex Conditions - MAKING SURE AT LEAST ONE CONDITION IS TRUE

Other times you'll want to check a series of conditions, but you only need one to be true. For example, say you've added a keyboard control for visitors to jump from picture to picture in a photo gallery. When the visitor presses the N key, the next photo appears. In this case, you want her to go to the next picture when she types either n (lowercase), or if she has the Caps Lock key pressed, N (uppercase). You're looking for a kind of either/or logic: Either this key or that key was pressed. The logical OR operator, represented by two pipe characters (||), comes in handy: if (key == 'n' || key == 'N') { //move to the next photo } When testing multiple conditions, it's sometimes difficult to figure out the logic of the conditional statement. Some programmers group each condition in a set of parentheses to make the logic easier to grasp: if ((key == 'n') || (key == 'N')) { //move to the next photo }

Changing Multiple CSS Properties at Once

Pass what's called an object literal to the .css() function. Think of an object literal as a list containing pairs of property names and values. After each property name, you insert a colon (:) followed by a value; each name/value pair is separated by a comma, and the whole shebang is surrounded by braces ({}). Thus, an object literal for the two CSS property values above looks like this: { 'background-color' : '#FF0000', 'border' : '2px solid #FE0037' } To use an object literal with the css() function, just pass the object to the function like this: $('#highlightedDiv').css({ 'background-color' : '#FF0000', 'border' : '2px solid #FE0037' });

How to Add JavaScript to a Page. Here are some tips on which URL type to use:

Root-relative paths are good for JavaScript files stored on your own site. Because they always start at the root folder, the URL for a JavaScript file will be the same for every page on your website, even when web pages are located in folders and subfolders on your site.However, root-relative paths don't work unless you're viewing your web pages through a web server—either your web server out on the Internet, or a web server you've set up on your own computer for testing purposes. In other words, if you're just opening a web page off your computer using the browser's File→Open command, the web browser won't be able to locate, load, or run JavaScript files that are attached using a root-relative path. Document-relative paths are the best when you're designing on your own computer without the aid of a web server. You can create an external JavaScript file, attach it to a web page, and then check the JavaScript in a web browser simply by opening the web page off your hard drive. Document-relative paths work fine when moved to your actual, living, breathing website on the Internet, but you'll have to rewrite the URLs to the JavaScript file if you move the web page to another location on the server. This book uses document-relative paths, which will let you follow along and test the tutorials on your own computer without a web server.

Replacing and Removing Selections

Say the pop-up dialog box had an ID of popup; you can use the following code to delete it: $('#popup').remove(); The .remove() function isn't limited to just a single element. Say you want to remove all <span> tags that have a class of error; you can do this: $('span.error').remove(); Assume there's an <img> tag with an ID of product101 that you wish to replace with text. Here's how you do that with jQuery: $('#product101').replaceWith(<p>Added to cart</p>'); This code removes the <img> tag from the page and replaces it with a <p> tag.

Setting and Reading Tag Attributes - Classes 2

Say you have a button on a web page that, when clicked, changes the <body> tag's class. By so doing, you can add a complete stylistic change to a web page by crafting a second set of styles using descendant selectors. When the button is clicked again, you want the class removed from the <body> tag, so the page reverts back to its previous appearance. For this example, assume the button the visitor clicks to change the page's style has an ID of changeStyle and you want to toggle the class name altStyle off and on with each click of the button. Here's the code to do that: $('#changeStyle').click(function() { $('body').toggleClass('altStyle'); });

CHOOSING HOW TO ADD ITEMS TO AN ARRAY

Say you've created a page that lets visitors create a playlist of songs by clicking song names on the page. Because a playlist lists songs in the order they should be played, the order is important. 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. The push() and unshift() commands return a value. To be specific, once push() and unshift() complete their tasks, they supply the number of items that are in the array. Here's an example: var p = [0,1,2,3]; var totalItems = p.push(4,5); After this code runs, the value stored in totalItems is 6, because there are six items in the p array.

ADDING AN ITEM TO THE END OF AN ARRAY

Say you've created an array named properties: var properties = ['red', '14px', 'Arial']; At this point, the array has three items. Remember that the last item is accessed using an index that's one less than the total number of items, so in this case, the last item in this array is properties[2]. To add another item, you could do this: properties[3] = 'bold'; You can also use an array by using the array's length property as the index. For example, you can rewrite the last line of code like this: properties[properties.length] = 'bold'; You can also use an array's push() command, which adds whatever you supply between 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 end of the properties array: properties.push('bold'); One advantage of the push() command is that it lets you add more than one item to the array. For example, say you want to add three values to the end of an array named properties, you could do that like this: properties.push('bold', 'italic', 'underlined');

Modifying Web Pages: An Overview

Select an element on a page. An element is any existing tag, and before you can do anything with that element, you need to select it using JavaScript. For example, to make a page fade into view, you first must select the page's content (the <body> tag); to make a pop-up menu appear when you mouse over a button, you need to select that button. Even if you simply want to use JavaScript to add text to the bottom of a web page, you need to select a tag to insert the text inside, before, or after. Do something with the element. Change a property of the element; Add new content; Remove the element; Extract information from the element; Add/remove a class attribute.

Keeping Variables from Colliding - local and global

So far, the only situation we've discussed is the use of variables as parameters. But what about a variable that's created inside the function, but not as a parameter,like this: 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 script, and again in the first line inside the function. This situation is the same as with parameters—by typing var message inside the function, you've created a new variable inside the function's scope. This type of variable is called a local variable, as it's only visible within the walls of the function—the main script and other functions can't see or access this variable.

Document/Window Events - load

The load event fires when the web browser finishes downloading all of a web page's files: the HTML file itself, plus any linked images, Flash movies, and external CSS and JavaScript files. Web designers have traditionally used this event to start any JavaScript program thatmanipulated the web page. However, loading a web page and all its files can take a long time if there are a lot of graphics or other large linked files. In some cases, this meant the JavaScript didn't run for quite some time after the page was displayed in the browser. Fortunately, jQuery offers a much more responsive replacement for the load event

Built-In Functions

Some functions (sometimes called methods), like alert() or document.write(), which you encountered on, are specific to web browsers. In other words, they only work with web pages, so you won't find them when programming in other environments that use JavaScript (like Node.js, Adobe Photoshop, or Flash's JavaScript-based ActionScript). Other functions are universal to JavaScript and work anywhere JavaScript works. For example, isNaN() is a function that checks to see whether a particular value is a number—this function comes in handy when you want to see if a visitor has correctly supplied a number for a question that requires a numerical answer (for example, "How many widgets would you like?"). One quick way to identify a function is by the parentheses. For example, you can tell isNaN() is a function In addition, JavaScript lets you create your own functions, so you can make your scripts do things beyond what the standard JavaScript commands offer.

Advanced Event Management 2

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 variables to the on() function for different elements. Here's an example: var linkVar = { message:'Hello from a link'}; var pVar = { message:'Hello from a paragraph'}; function showMessage(evt) { alert(evt.data.message); } $('a').on('mouseover',linkVar,showMessage); $('p').on('click',pVar,showMessage); It creates two variables, linkVar on the first line and pVar on the second line. Each variable contains an object literal, with the same property name, message, but different message text. A function, showMessage(), takes the event object and stores it in a variable named evt. That function runs the alert() command, displaying the message property (which is itself a property of the event object's data property). Keep in mind that message is the name of the property defined in the object literal.

Adding Content to a Page .append()

The .append() function is a great way to add an item to the end of a bulleted (<ul>) or numbered (<ol>) list. As an example, say you run the following code on a page with the HTML listed at the beginning of this section: $('#errors').append('<p>There are four errors in this form</p>'); After this function runs, you end up with HTML like this: <div id="container"> <div id="errors"> <h2>Errors:</h2> <p>There are four errors in this form</p> </div> </div> .prepend() is just like .append(), but adds HTML directly after the opening tag for the selection. For example, say you run the following code on the same HTML listed previously: $('#errors').prepend('<p>There are four errors in this form</p>');

Reading, Setting, and Removing HTML Attributes

The attr() function lets you read a specified HTML attribute from a tag. For example, to determine the current graphic file a particular <img> points to, you pass the string 'src' (for the <img> tag's src property) to the function: var imageFile = $('#banner img').attr('src'); If you pass a second argument to the attr() function, you can set the tag's attribute. For example, to swap in a different image, you can change an <img> tag's src property like this: $('#banner img').attr('src','images/newImage.png'); If you want to completely remove an attribute from a tag, use the removeAttr() function. For example, this code removes the bgColor property from the <body> tag: $('body').removeAttr('bgColor');

Form Events - blur

The blur event is the opposite of focus. It's triggered when you exit a currently focused field, by either tabbing or clicking outside the field. The blur event is another useful time for form validation. For example, when someone types her email address in a text field, then tabs to the next field, you could immediately check what she's entered to make sure it's a valid email address.

CSS components: 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 (}).

More Complex Conditions - NEGATING A CONDITION

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 the NOT operator, then reverse it. In other words, if the condition results to true, the ! operator changes it to false, so the conditional statement doesn't run.

this and $(this) part 2

The first step in the anonymous function is to retrieve the URL for the link. Because each link has a different URL, you must access the current element each time through the loop. The $(this) keyword lets you do just that: $('a[href^=http://]').each(function() { var extLink = $(this).attr('href'); }); The code in the middle, bolded line does several things: First, it creates a new variable (extLink) and stores the value of the current element's href property. Each time through the loop, $(this) refers to a different link on the page, so each time through the loop, the extLink variable changes. After that, it's just a matter of appending a new list item to the <ul> tag (see the HTML above), like this: $('a[href^=http://]').each(function() { var extLink = $(this).attr('href'); $('#bibList').append('<li>' + extLink + '</li>'); });

Keyboard Events - keydown

The keydown event is like the keypress event—it's fired when you press a key. Actually, it's fired right before the keypress event. In Opera, the keydown event only fires once. In other browsers, the keydown event behaves just like the keypress event—it fires over and over as long as the key is pressed. Finally, the keyup event is triggered when you release a key.

Keyboard Events - keypress

The moment you press a key, the keypress event fires. You don't have to let go of the key, either. In fact, the keypress event continues to fire, over and over again, as long as you hold the key down, so it's a good way to see if a visitor is holding down the key. For example, if you created a web racecar game you could assign a key to the gas pedal. The player only has to press the key down and hold it down to make the car move.

Mouse Events - mousedown

The mousedown event is the first half of a click—the moment when you click the button before releasing it. This event is handy for dragging elements around a page. You can let visitors drag items around your web page just like they drag icons around their desktop—by clicking on them (without releasing the button) and moving them, and then releasing the button to drop them. The mouseup event is the second half of a click—the moment when you release the button. This event is handy for responding to the moment when you drop an item that has been dragged. When you move your mouse over an element on a page, a mouseover event fires. You can assign an event handler to a navigation button using this event and have a submenu pop up when a visitor mouses over the button. (If you're used to the CSS :hover pseudo-class, then you know how this event works.) Moving a mouse off an element triggers the mouseout event. You can use this event to signal when a visitor has moved her mouse off the page, or to hide a pop-up menu when the mouse travels outside the menu. Logically enough, the mousemove event fires when the mouse moves—which means this event fires all of the time. You use this event to track the current position of the cursor on the screen. In addition, you can assign this event to a particular tag on the page—a <div>, for example—and respond only to movements within that tag.

How to Add JavaScript to a Page

The part of the web browser that understands HTML and CSS is called the layout or rendering engine. But most browsers also have something called a JavaScript interpreter. That's the part of the browser that understands JavaScript and can execute the steps of a JavaScript program. The web browser is usually expecting HTML, so you must specifically tell the browser when JavaScript is coming by using the <script> tag. Much of the time, you'll add the <script> tag in the web page's <head> section, like this: <title>My Web Page</title> <script type="text/javascript"> </script> </head>

Document/Window Events - scroll

The scroll event is triggered whenever you drag the scroll bar, or use the keyboard (for example, the up, down, home, end, and similar keys) or mouse scroll wheel to scroll a web page. If the page doesn't have scrollbars, no scroll event is ever triggered. Some programmers use this event to help figure out where elements (after a page has scrolled) appear on the screen.

CSS components: Selectors

The selector tells a web browser which element or elements on a page to style—like a headline, paragraph, image, or link. i.e p {

Stopping an Event in Its Tracks

The stopPropagation() function prevents an event from passing onto any ancestor tags. The function is a method of the event object, so you access it within an event- handling function: $('#theLink').click(function(evt) { // do something evt.stopPropagation(); // stop event from continuing });

Accessing Items in an Array

To access a particular item in an array, you use that item's index number. For example, say you've created an array with abbreviations for the days of the week, and want to open an alert box that displayed the first item. You could write this: var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; alert(days[0]); This code opens an alert box with 'Mon' in it. Arrays are zero-indexed, meaning that the first item in an array has an index value of 0, and the second item has an index value of 1. You can use this tricky bit of JavaScript to access the value stored in the last item in the array: days[days.length-1] You can also use a variable containing a number as the index: var i = 0; alert(days[i]); The last line of code is the equivalent of alert(days[0]);. You'll find this technique particularly useful when working with loops, as described in the next chapter

Creating an Array

To create an array, 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, var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; var playList = []; Creating an empty array is the equivalent of declaring a variable. You'll create an empty array when you don't add items to the array until the program is running. For example, the above array might be used to track songs that someone selects from a list on a web page. You don't know ahead of time which songs the person will choose, so you declare an empty array and later fill it with items as the person selects music.

Reading and Changing CSS Properties

To determine the current value of a CSS property, pass the name of the property to the css() function. For example, say you want to find the background color of a <div> tag with an ID of main: var bgColor = $('#main').css('background-color'); After this code runs, the variable bgColor will contain a string with the element's background color value. To change the font size for the <body> tag to 200%, you can do this: $('body').css('font-size', '200%'); var baseFont = $('body').css('font-size'); baseFont = parseInt(baseFont); $('body').css('font-size',baseFont * 2); The first line retrieves the <body> tag's font-size value—the returned value is in pixels and is a string like this: '16px'. Because you want to double that size—multiplying it by 2—you must convert that string to a number by removing the "px" part of the string. The second line accomplishes that using the JavaScript parseInt() method discussed on page 562. That function essentially strips off anything following the number, so after line 2, baseFont contains a number, like 16. Finally, the third line resets the font-size property by multiplying the baseFont value by 2.

this and $(this)

To help make clear how to use $(this), take another look at the task described at the beginning of this section—creating a list of external links in a bibliography box at the bottom of a page. Assume that the page's HTML already has a <div> tag ready for the external links. For example: <div id="bibliography"> <h3>Web pages referenced in this article</h3> <ul id="bibList"> </ul> </div> The first step is to get a list of all links pointing outside your site. You can do so using an attribute selector: $('a[href^="http://"]') Now to loop through each link, add the each() function: $('a[href^="http://"]').each() Then add an anonymous function: $('a[href^="http://"]').each(function() { });

Retrieving Information from Functions

To return a value from your own functions, you use return followed by the value you wish to return: function functionName(parameter1, parameter2) { // the JavaScript you want to run return value; } For example, say you want to calculate the total cost of a sale including sales tax. You might create a script like this: var TAX = .08; // 8% sales tax function calculateTotal(quantity, price) { var total = quantity * price * (1 + TAX); var formattedTotal = total.toFixed(2); return formattedTotal; } To make use of the return value, you usually store it inside a variable. So in this example, you could call the function like this: var saleTotal = calculateTotal(2, 16.95); document.write('Total cost is: $' + saleTotal);

jQuery Filters

To use a filter, you add a colon followed by the filter's name after the main selector. For example, to find every even row of a table, write your jQuery selector like this: $('tr:even') These filters work a little counter-intuitively; just remember that a jQuery selection is a list of all elements that match a specified selector. In that respect, they're kind of like arrays. Each element in a jQuery selection has an index number—remember that index values for arrays always start at 0. So, since :even filters on even index values (like 0, 2, and 4), this filter actually returns the first, third, and fifth items (and so on) in the selection—in other words, it's really selecting every other odd element! The :odd filter works the same except it selects every odd index number (1, 3, 5, and so on).

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 you don't give it a name. Here's an anonymous function's basic structure: Here's how you incorporate an anonymous function as part of the each() function: $('selector').each(function() { // code goes in here }); Say you have 50 images on a page and add the following JavaScript code to one of the page's scripts: $('img').each(function() { alert('I found an image'); }); 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.)

Tips for Writing Conditional Statements - Type both of the curly braces before you type the code inside them

Type both of the curly braces before you type the code inside them. One of the most common mistakes programmers make is forgetting to add a final brace to a conditional statement. To avoid this mistake, type the condition and the braces first, then type the JavaScript code that executes when the condition is true. For example, start a conditional like this: if (dayOfWeek=='Friday') { }

Keyboard Events

Web browsers also track when visitors use their keyboards, so you can assign commands 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 browsers handle keyboard events differently, even making it hard to tell which letter was entered!

Mouse Events - clicks

Web browsers provide lots of ways of tracking how a visitor uses a mouse to interact with a web page: The click event fires after you click and release the mouse button. You'll commonly assign a click event to a link: For example, a link on a thumbnail image can display a larger version of that image when clicked. However, you're not limited to just links. You can also make any tag on a page respond to an event—even just clicking anywhere on the page.

Waiting for the HTML to Load

When a page loads, a web browser tries immediately to run any scripts it encounters. So scripts in the head of a page might run before the page fully loads—you saw this in the Moon Quiz tutorial on page 94, where the page was blank until the script asking the questions finished. Unfortunately, this phenomenon often causes problems. The most common way to deal with that problem has been to use a web browser's onload event to wait until a page is fully downloaded and displayed before executing any JavaScript. The onload event only fires after all of a web page's files have downloaded. If the JavaScript makes a lot of changes to the page visitors will suddenly see the page change before their very eyes. Fortunately, jQuery comes to the rescue. Instead of relying on the load event to trigger a JavaScript function, jQuery has a special function named ready() that waits just until the HTML has been loaded into the browser and then runs the page's scripts. That way, the JavaScript can immediately manipulate a web page without having to wait for slow-loading images or movies. You've already used the ready() function in a few of the tutorials in this book. The basic structure of the function goes like this: $(document).ready(function() { //your code goes here });

Understanding the Document Object Model

When a web browser loads an HTML file, it displays the contents of that file on the screen. But that's not all the web browser does with the tags, attributes, and contents of the file: It also creates and memorizes a "model" of that page's HTML. In other words, the web browser remembers the HTML tags, their attributes, and the order in which they appear in the file—this representation of the page is called the Document Object Model, or DOM for short. The DOM provides the information JavaScript needs to communicate with the elements on the web page. The DOM also provides the tools necessary to navigate through, change, and add to the HTML on the page. The DOM itself isn't actually JavaScript—it's a standard from the World Wide Web Consortium (W3C) that most browser manufacturers have adopted and added to their browsers. The DOM lets JavaScript communicate with and change a page's HTML. In addition to HTML tags, web browsers also keep track of the text that appears inside a tag, as well as the attributes that are assigned to each tag. In fact, the DOM treats each of these—tags (also called elements), attributes, and text—as individual units called nodes.

Seeing Double <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 of script tags appears in the head, because you want the prompt window to appear earlier. If you move the prompt() method down in the body (go ahead and try it), you'll see that when the page loads, only a part of the page gets displayed when the prompt appears. Because the JavaScript at that point runs immediately, before any of the other parts of the page displays, the web browser has to wait until the visitor fills out the prompt window before it can display the rest of the page. In other words, the page looks page.

Document/Window Events - unload

When you click a link to go to another page, close a browser tab, or close a browser window, a web browser fires an unload event. It's like the last gasp for your JavaScript program and gives you an opportunity to complete one last action before the visitor moves on from your page. Nefarious programmers have used this event to make it very difficult to ever leave a page. Each time a visitor tries to close the page, a new window appears and the page returns. But you can also use this event for good: For example, a program can warn a visitor about a form he's started to fill out but hasn't submitted, or the program could send form data to the web server to save the data before the visitor exits the page.

Mouse Events - dblclick

When you press and release the mouse button twice quickly, a doubleclick (dblclick) event fires. It's the same action you use to open a folder or file on your desktop. Double-clicking a web page isn't a usual web-surfer action, so if you use this event, you should make clear to visitors where they can doubleclick and what will happen after they do. Also note each click in a double-click event also fires two click events, so don't assign click and dblclick events to the same tag. Otherwise, the function for the click will run twice before the dblclick function runs.

Document/Window Events - resize

When you resize your browser window by clicking the maximize button, or dragging the browser's resize handle, the browser triggers a resize event. Some designers use this event to change the layout of the page when a visitor changes the size of his browser. For example, after a visitor resizes his browser window, you can check the window's width—if the window is really wide, you could change the design to add more columns of content to fit the space.

Understanding jQuery Selections

When you select one or more elements using the jQuery object—for example, $('#navBar a')—you don't end up with a traditional list of DOM nodes, like the ones you get if you use getElementById() or getElementsByTagName(). Instead, you get a special jQuery-only selection of elements. These elements don't understand the traditional DOM methods; so, if you learned about the DOM in another book, you'll find that none of the methods you learned there works with the jQuery object as is. That may seem like a major drawback, but nearly all of the properties and methods of a normal DOM node have jQuery equivalents, so you can do anything the traditional DOM can do—only usually much faster and with fewer lines of code. There are, however, two big conceptual differences between how the DOM works and how jQuery selections work. jQuery was built to make JavaScript easier and faster to program. One of the goals of the library is to let you do a lot of stuff with as few lines of code as possible. To achieve that, jQuery uses two unusual principles: automatic loops and chaining functions.

Form Events - focus

When you tab or click into a text field, it gives the field focus. In other words, the browser's attention is now focused on that page element. Likewise, selecting a radio button, or clicking a checkbox, gives those elements focus. You can respond to the focus event using JavaScript. For example, you could add a helpful instruction inside a text field—"Type your full name." When a visitor clicks in the field (giving it focus), you can erase these instructions, so he has an empty field he can fill out.

Form Events - submit

Whenever a visitor submits a form, the submit event fires. A form might be submitted by clicking the Submit button, or simply by hitting the Enter (Return) key while the cursor is in a text field. You'll most frequently use the submit event with form validation—to make sure all required fields are correctly filled out before the data is sent to the web server.

The Event Object

Whenever a web browser fires an event, it records information about the event and stores it in an event object. The event object contains information that was collected when the event occurred, like the vertical and horizontal coordinates of the mouse, the element on which the event occurred, or whether the Shift key was pressed when the event was triggered. 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 of the cursor when the mouse is clicked anywhere on a page: $(document).click(function(evt) { var xPos = evt.pageX; var yPos = evt.pageY; alert('X:' + xPos + ' Y:' + yPos); }); // end click The important part here is the evt variable. When the function is called (by clicking anywhere in the browser window), the event object is stored in the evt variable. Within the body of the function, you can access the different properties of the event object using dot syntax—for example, evt.pageX returns the horizontal location of the cursor (in other words, the number of pixels from the left edge of the window).

Selecting Page Elements: The jQuery Way

With jQuery, you select one or more elements using a special command called the jQuery object. The basic syntax is like this: $('selector') You can use nearly all CSS 2.1 and many CSS 3 selectors when you create a jQuery object (even if the browser itself doesn't understand the particular selector—like certain CSS3 selectors in older versions of IE). For example, if you want to select a tag with a specific ID of banner in jQuery, you can write this: $('#banner') Say you want to change the HTML inside an element. You can write the following line: $('#banner').html('<h1>JavaScript was here</h1>'); Once you select those tags, you can manipulate them using jQuery. For example, to hide all tags with the class name of .submenu, you'd write this: $('.submenu').hide();

Tips for Writing Conditional Statements - Indent code within braces

You can better visualize the structure of a conditional statement if you indent all of the JavaScript between a pair of braces: if (a < 10 && a > 1) { alert("The value " + a + " is between 1 and 10"); } Use == for comparing equals. When checking whether two values are equal, don't forget to use the equality operator, like this: if (name == 'Bob') { A common mistake is to use a single equals sign, like this: if (name = 'Bob') {

Stopping an Event's Normal Behavior

You can prevent the web browser's normal response to an event with the preventDefault() function. This function is actually a part of the event object, so you'll access it within the function handling the event. For example, say a page has a link with an ID of menu. The link actually points to another menu page (so visitors with JavaScript turned off will be able to get to the menu page). However, you've added some clever JavaScript, so when a visitor clicks the link, the menu appears right on the same page. Normally, a web browser would follow the link to the menu page, so you need to prevent its default behavior, like this: $('#menu').click(function(evt){ // clever javascript goes here evt.preventDefault(); // don't follow the link }); Another technique is simply to return the value false at the end of the event function. For example, the following is functionally the same as the code above: $('#menu').click(function(evt){ // clever javascript goes here return false; // don't follow the link });

More Complex Conditions - MAKING SURE MORE THAN ONE CONDITION IS TRUE

You'll often need to make decisions based on a combination of factors. For example, you may only want to go to a movie if you have enough money and there's a movie you want to see. In this case, you'll go only if two conditions are true; if either one is false, then you won't go to the movie. In JavaScript, you can combine conditions using what's called the logical AND operator, which is represented by two ampersands (&&). You can use it between the two conditions within a single conditional statement. For example, if you want to check if a number is between 1 and 10, you can do this: if (a > 1 && a < 10) { //the value in a is between 1 and 10 alert("The value " + a + " is between 1 and 10"); } You're not limited to just two conditions. You can connect as many conditions as you need with the && operator: if (b>0 && a>0 && c>0) { // all three variables are greater than 0 } This code checks three variables to make sure all three have a value greater than 0. If just one has a value of 0 or less, then the code between the braces won't run.

Using Events the jQuery Way 1. Select one or more elements.

jQuery programming involves (a) selecting a page element and then (b) doing something with that element. In fact, because events are so integral to JavaScript programming, it's better to think of jQuery programming as a three-step process: 1. Select one or more elements. The previous chapter explained how jQuery lets you use CSS selectors to choose the parts of the page you want to manipulate. When assigning events, you want to select the elements that the visitor will interact with. For example, what will a visitor click—a link, a table cell, an image? If you're assigning a mouseover event, what page element does a visitor mouse over to make the action happen?

Setting and Reading Tag Attributes - Classes

jQuery provides several functions for manipulating a tag's class attribute: • addClass() adds a specified class to an element. You add the addClass() after a jQuery selection and pass the function a string, which represents the class name you wish to add. For example, to add the class externalLink to all links pointing outside your site, you can use this code: $('a[href^="http://"]').addClass('externalLink'); This code would take HTML like this: <a href="http://www.oreilly.com/"> And change it to the following: <a href="http://www.oreilly.com/" class="externalLink"> When using the addClass() and removeClass() functions, you only supply the class name—leave out the period you normally use when creating a class selector. For example, addClass('externalLink') is correct, but addClass('.externalLink') is wrong.

Two ways of removing an item from an array

pop() / var p = [0,1,2,3] / p.pop() / [0,1,2] shift() var p = [0,1,2,3] / p.shift() / [1,2,3]

Adding Content to a Page .text()

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 it. Say, after running a program to check to see if there were any errors in the form, you wanted to replace the text "Errors:" with "No errors found", you could use this code: $('#errors h2').text('No errors found');

Handling Repetitive Tasks with Loops - Loops and Arrays

var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; 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++; }


Set pelajaran terkait

Chapter 6 - other sensation systems

View Set

AJS212 / Juvenile Justice - Ch. 10 & 11

View Set

PNU 128 Videbeck PrepU Chapter 19:Addiction

View Set

vSim Health Assessment | Edith Johnson (Neurological Assessment)

View Set

Maternity Exam 1 - Chapter Q&A - Chapter 3, 4, 5, 10, 11, 12, 19, 20

View Set

Chapter 7: Food Deterioration and Its Control

View Set

Interpersonal Communications: Chapter 1

View Set

AP Human Geography - AP Test Review

View Set