You are previewing Head First jQuery.

Head First jQuery

Cover of Head First jQuery by Ryan Benedetti... Published by O'Reilly Media, Inc.
  1. Head First jQuery
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Advance Praise for Head First jQuery
  5. Praise for other Head First books
  7. How to use this book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. And we know what your brain is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did
    6. Here’s what YOU can do to bend your brain into submission
    7. Read me
    8. Software requirements
    9. Download jQuery
    10. Folder setup
    11. The technical review team
    12. Acknowledgments
    13. Safari® Books Online
  8. 1. Getting Started with jQuery: Web Page Action
    1. You want web page power
    2. HTML and CSS are fine, but...
    3. need the power of script
    4. Enter jQuery (and JavaScript)!
    5. Look into the browser
    6. The hidden structure of a web page
    7. jQuery makes the DOM less scary
    8. How does that work?
      1. Introducing the jQuery function (and shortcut)
    9. jQuery selects elements the same way CSS does
    10. Style, meet script
    11. jQuery selectors at your service
    12. jQuery in translation
    13. Your first jQuery gig
      1. Revisit your requirements
    14. Set up your HTML and CSS files
    15. Slide on in...
    16. May the fade be with you
    17. That’s it?
    18. You rescued the Furry Friends campaign
    19. Your jQuery Toolbox
  9. 2. Selectors and Methods: Grab and Go
    1. Jump for Joy needs your help
    2. What are the project requirements?
    3. Dig in with divs
    4. A click event up close
    5. Add the click method to your page
    6. Get more specific
    7. Classing up your elements
    8. ID-entifying elements
    9. Wire up your web page
    10. Meanwhile, back to our list
    11. Creating some storage space
    12. Mix things up with concatenation
    13. Meanwhile, back in the code...
    14. Insert your message with append
    15. Everything works great, but...
    16. Give me $(this) one
    17. Put $ (this) to work
    18. Good riddance with remove
    19. Dig down with descendant selectors
    20. Your turn to jump for joy
    21. Your jQuery Toolbox
  10. 3. jQuery Events and Functions: Making Things Happen on Your Page
    1. Your jQuery skillz are in demand again
    2. The money man has a point...
    3. Making your page eventful
    4. Behind the scenes of an event listener
    5. Binding an event
      1. Method 1
      2. Method 2
    6. Triggering events
    7. Removing an event
      1. To remove one event
      2. To remove all events
    8. Going through the motions elements
    9. Your project structure
    10. Making things function-al
    11. The nuts and bolts of a function
      1. Giving functions names
    12. The anonymous function
    13. Named functions as event handlers
      1. Function declaration
      2. Function expression
    14. Passing a variable to a function
    15. Functions can return a value, too
    16. Use conditional logic to make decisions
    17. Jump for Joy needs even more help
    18. Methods can change the CSS
    19. Add a hover event
    20. You’re almost there...
    21. Your jQuery Toolbox
  11. 4. jQuery Web Page Manipulation: Mod the DOM
    1. The Webville Eatery wants an interactive menu
    2. Go vegetarian
    3. Class up your elements
    4. Button things up
    5. What’s next?
    6. Swinging through the DOM tree
    7. Traversal methods climb the DOM
    8. Chain methods to climb farther
    9. Variables can store elements, too
    10. There’s that dollar sign again...
    11. Expand your storage options with arrays
    12. Store elements in an array
    13. Change out elements with replaceWith
    14. How can replaceWith help?
    15. Think ahead before using replaceWith
    16. replaceWith doesn’t work for every situation
      1. One–to–many substitution
      2. Many–to–one substitution
    17. Insert HTML content into the DOM
    18. Use filter methods to narrow your selections (Part 1)
    19. Use filter methods to narrow your selections (Part 2)
    20. Bring the burger back
    21. Where’s the beef (er...meat)?
    22. A meaty array
    23. The each method loops through arrays
    24. That’s it...right?
    25. Your jQuery Toolbox
  12. 5. jQuery Effects and Animation: A Little Glide in Your Stride
    1. DoodleStuff needs a web app
    2. Do the Monster Mashup
    3. Monster Mashup needs layout and positioning
    4. A little more structure and style
    5. Make the interface click
    6. Make the lightning effect
    7. How does jQuery animate elements?
      1. hide, show, and toggle change the CSS display property
    8. Fade effects animate the CSS opacity property
    9. Sliding is all about height
    10. Put fade effects to work
    11. Combine effects with method chains
    12. Striking back with a timed function
    13. Add the lightning functions to your script
    14. DIY effects with animate
      1. Motion effects
      2. Scale effects
    15. What can and can’t be animated
      1. Text effects
    16. animate changes style over time
    17. From where to where exactly?
    18. Absolute vs. relative element movement
      1. Relative animation = move it this much each time
    19. Move stuff relatively with operator combinations
    20. Add the animate functions to your script
    21. Look, Ma, no Flash!
    22. Your jQuery Toolbox
  13. 6. jQuery and JavaScript: Luke jQuery, I Am Your Father!
    1. Spicing up the Head First Lounge
    2. Objects offer even smarter storage
    3. Build your own objects
      1. UML diagram of an object
    4. Create reusable objects with object constructors
    5. Interacting with objects
    6. Set up the page
    7. The return of arrays
    8. Accessing arrays
    9. Add and update items in arrays
    10. Perform an action over (and over, and over...)
    11. Looking for the needle in a haystack
    12. Decision making time...again!
    13. Comparison and logical operators
    14. Clearing things up with jQuery...
      1. ... is even easier in JavaScript
    15. Add some extra excitement
    16. Your jQuery/JavaScript Toolbox
  14. 7. Custom Functions for Custom Effects: What Have You Done for Me Lately?
    1. A storm is brewing
    2. We’ve created a monster...function
    3. Get control of timed effects with the window object
    4. Respond to browser events with onblur and onfocus
    5. Timer methods tell your functions when to run
    6. Write the stopLightning and goLightning functions
    7. Feature request for Monster Mashup
    8. Let’s get (more) random
    9. You already know the current position...
    10. ...and the getRandom function too
    11. Move relative to the current position
      1. Scenario 1: target > current
      2. Scenario 2: target < current
    12. Monster Mashup v2 is a hit!
    13. Your jQuery Toolbox
  15. 8. jQuery and Ajax: Please Pass the Data
    1. Bring the Bit to Byte race into this century
    2. Looking at last year’s page
      1. Configuring a plug-in
    3. Getting dynamic
    4. OLD web, meet the NEW web
      1. Enter Ajax
    5. Understanding Ajax
    6. The X factor
      1. XML doesn’t DO anything
    7. GETting data with the ajax method
    8. Parsing XML data
    9. Scheduling events on a page
    10. Self-referencing functions
    11. Getting more from your server
      1. Server-side languages to the rescue!
    12. What time is it?
    13. Turning off scheduled events on your page
    14. Your jQuery/Ajax Toolbox
  16. 9. Handling JSON Data: Client, Meet Server
    1. Webville MegaCorp’s Marketing Department doesn’t know XML
    2. XML errors break the page
    3. Collect data from a web page
    4. What to do with the data
    5. Format the data before you send it
    6. Send the data to the server
    7. Store your data in a MySQL database
    8. Create your database to store runner info
    9. Anatomy of an insert statement
    10. Use PHP to access the data
    11. Handle POST data on the server
    12. Connect to a database with PHP
    13. Use select to read data from a database
    14. Get data with PHP
    15. JSON to the rescue!
    16. jQuery + JSON = Awesome
    17. A few PHP rules...
      1. PHP basics
      2. Rules for variables
      3. Rules for loops
    18. A few (more) PHP rules...
      1. Rules for arrays
      2. Rules for conditionals
      3. Rules for writing to the screen
    19. Format the output using PHP
    20. Access data in the JSON object
    21. Data sanitization and validation in PHP
      1. Use the same PHP file for multiple purposes
    22. Your jQuery/Ajax/PHP/MySQL Toolbox
  17. 10. jQuery UI: Extreme Form Makeover
    1. needs a makeover
    2. Pimp your HTML form
    3. Save coding headaches (and time) with jQuery UI
    4. What’s inside the jQuery UI package
      1. Our project checklist
    5. Build a date picker into the sightings form
    6. jQuery UI behind the scenes
    7. Widgets have customizable options
      1. Customize the datepicker with options
      2. The datepicker works!
      3. Check it off
    8. Styling up your buttons
      1. Grouping button widgets
    9. Control numerical entries with a slider
      1. The HTML for a slider widget
      2. The jQuery script for a slider widget
    10. Computers mix color using red, green, and blue
      1. Your sliders need to do the same
    11. Build the refreshSwatch function
    12. One last little thing...
    13. Your jQuery Toolbox
  18. 11. jQuery and APIs: Objects, Objects Everywhere
    1. Where’s Waldo Sasquatch?
    2. The Google Maps API
    3. APIs use objects
    4. Include Google maps in your page
    5. Getting JSON data with SQL and PHP
    6. Points on a map are markers
    7. Multicreature checklist
    8. Listening for map events
    9. You did it!
    10. Your jQuery API Toolbox
    11. Leaving town...
    12. It’s been great having you in jQueryville!
  19. A. Leftovers: The Top Ten Things (We Didn’t Cover)
    1. #1. Every single thing in the jQuery library
      1. jQuery methods
      2. jQuery selectors
    2. #2. jQuery CDNs
    3. #3. The jQuery namespace: noConflict method
    4. #4. Debugging your jQuery code
    5. #5. Advanced animation: queues
    6. #6. Form validation
    7. #7. jQuery UI effects
    8. #8. Creating your own jQuery plug-ins
    9. #9. Advanced JavaScript: closures
    10. #10. Templates
  20. B. Set Up a Development Environment: Get Ready for the Big Times
    1. Create a PHP development environment
    2. Find out what you have
    3. Do you have a web server?
    4. Do you have PHP? Which version?
    5. Do you have MySQL? Which version?
    6. Start with the web server
    7. Apache installation...concluded
    8. PHP installation
    9. PHP installation steps
    10. PHP installation steps...concluded
    11. Installing MySQL
      1. Instructions and troubleshooting
    12. Steps to install MySQL on Windows
      1. Download your installer
      2. Pick a destination folder
    13. Enabling PHP on Mac OS X
    14. Steps to install MySQL on Mac OS X
      1. Download your installer
      2. Run the package installer
  21. Index
  22. About the Authors
  23. Copyright
O'Reilly logo

Chapter 1. Getting Started with jQuery: Web Page Action

image with no caption

You want more for your web pages. You’ve got HTML and CSS under your belt and want to add scripting to your skill set, but you don’t want to spend your life writing lines and lines of script. You need a scripting library that allows you to change web pages on the fly. And since we’re wishing, can it play well with AJAX and PHP, too? Can it do in 3 lines of code what most client-side languages do in 15? Wishful thinking? No way! You need to meet jQuery.

You want web page power

You already know how to build great-looking web pages with clean, valid HTML and CSS. But static web pages just don’t cut it anymore—people want a responsive web page. They want action, animation, interaction, and lots of cool effects.

image with no caption
image with no caption

HTML and CSS are fine, but...

Plain old HTML and CSS are good for giving your page structure and style. Once you have a rendered HTML page, it’s there, but it’s static.

What if you want to change how the page looks, or add or remove something from it? You either have to do some really crazy CSS gymnastics, or you simply have to load a new page. And that can get ugly fast. Why? Because all you’re really doing with HTML and CSS is controlling how a page is displayed.

  1. The browser requests a web page from a server when someone types a web address into the browser’s URL bar.

    image with no caption
  2. The server finds the requested file(s) and sends them to the browser.

  3. The browser displays a rendered HTML page based on the file sent from the server.

    image with no caption need the power of script

To change your web pages on the fly, without reloading, you need to talk to your browser. How do you pull that off? With an HTML tag known as <script>.

image with no caption
image with no caption

Great question. Remember that HTML is a markup language that handles document structure.

And cascading style sheets (CSS) control the look and feel and position of those elements. HTML and CSS control how a web page is built and displayed, but neither of them can add behavior to the web page. What we need for that is a scripting language. What we need is jQuery.

Enter jQuery (and JavaScript)!

The language we use to give the browser directions is JavaScript. Every browser comes with a built-in JavaScript interpreter that takes the directions you write in between the <script> tags and translates those directions into different kinds of action on the web page.

image with no caption

To give the interpreter directions, you ultimately need to speak JavaScript. But don’t worry! This is where jQuery comes in. jQuery is a JavaScript library specialized for changing web page documents on the fly. Let’s check some jQuery out.

jQuery is a JavaScript library specialized for changing web page documents on the fly.

image with no caption

That’s a great question. It does seem a bit like magic, right?

Let’s look at a web page from the perspective of the browser—specifically, how jQuery can change the web page from within the browser.

Look into the browser

It’s time to pull back the curtain to see what’s really going on behind a web page as a browser displays it. Your browser uses the HTML Document Object Model (DOM) to build a page from simple HTML markup and CSS code into a clickable page complete with text, images, videos, and all the other great content we love to browse.

  1. The browser loads the HTML file it gets from the server.

    image with no caption


    This stuff all happens inside the browser.

  2. The browser’s layout engine goes through the HTML and CSS to build a “document” using the HTML Document Object Model (DOM).

    image with no caption
  3. The browser displays a rendered page in the browser’s viewport.

    image with no caption
  4. The JS interpreter references the DOM to make changes to the web page without needing to reload it.

    image with no caption

The hidden structure of a web page

Over the years, the DOM has helped HTML, CSS, and JavaScript work together more effectively. It provides a standardized skeleton that all modern browsers use to make browsing the Web more effective. Many people think of the DOM as being built like a tree: it has a root and branches with nodes at the end. Alternatively, you can think of it as an x-ray for how the page is built.

image with no caption
image with no caption
image with no caption

An x-ray tells a doctor what’s going on with the body’s hidden structure. Like an x-ray, the DOM shows us the hidden structure behind the page. But unlike an x-ray, JavaScript and jQuery use the DOM to change the structure on the page.

jQuery makes the DOM less scary

The DOM can seem complex and intimidating, but luckily for us, jQuery keeps it simple. Don’t forget: jQuery is JavaScript, but a much more approachable version. When you want to control the DOM, jQuery makes it much easier. For instance, let’s say we want to change the HTML inside of the only paragraph element on our page.

image with no caption

Or let’s say we want to change the HTML inside of five paragraph elements on our page:

image with no caption

One of jQuery’s main strengths is that it allows you to work with the DOM without having to know every little thing about it. Underneath it all, JavaScript is doing the heavy lifting. Throughout this book, you’ll learn to use JavaScript and jQuery together. In Chapter 6, we’ll learn more about jQuery’s relationship to JavaScript, and we’ll beef up our JavaScript skills along the way. For now, when you need to work with the DOM, you’ll use jQuery.

Let’s take jQuery for a spin around DOM-ville, shall we?

How does that work?

Pretty nifty how jQuery can manipulate the page, isn’t it? The important part to keep in mind is that none of the original HTML and CSS changed when you pressed each button. So how did jQuery do it? Check it out:

image with no caption

The JavaScript interpreter doesn’t change the original HTML and CSS files. It makes changes to the DOM’s representation of the page in the browser’s memory.

image with no caption

The dollar sign represents all of the cash you’ll rake in with your newly acquired jQuery skills. Kidding, but it does bring home the bacon in the jQuery world.

Introducing the jQuery function (and shortcut)

The dollar sign with the parentheses is the shorter name of the jQuery function. This shortcut saves us from writing “jQuery ()” every time we want to call the jQuery function. The jQuery function is also often referred to as the jQuery wrapper.

image with no caption

The short name and the long name point to the same thing: the big code block known as jQuery. Throughout this book, we’ll use the shortcut. Here are three different things you can put into the jQuery function.

image with no caption

jQuery selects elements the same way CSS does

You already know more about jQuery than you realize. The main way you get at stuff with jQuery is to use selectors—the same selectors you’ve used with CSS. If you’re a little fuzzy on CSS selectors, it’s OK. Let’s have a quick refresher.

image with no caption

Style, meet script

The great thing about jQuery is that it uses those same CSS selectors we use to style our page to manipulate elements on the page.

image with no caption

CSS selectors select elements to add style to those elements; jQuery selectors select elements to add behavior to those elements.


You’ll do more with combining selectors and methods in Chapter 2 and the rest of this book.

jQuery selectors at your service

As its name suggests, jQuery is all about querying. You ask for something with a selector, and the JavaScript interpreter asks the DOM to get it for you. If you ask for an element with nested elements, jQuery will give you the nested elements too. Let’s take apart a jQuery selector a bit more to make sure we know how it works.

image with no caption
image with no caption

jQuery in translation

To show you just how easy it is to learn jQuery, here’s a little breakdown of a few jQuery phrases to use when travelling in DOM country.

image with no caption
image with no caption
image with no caption

Your first jQuery gig

You just landed a job as the new web developer for the Webville Pet Rescue Foundation. The marketing team wants to kick off their annual fundraising campaign with a revamp of last year’s “Help Our Furry Friends” web page. They gave you a screen shot from last year with details on what they want the page to do.

image with no caption

Well, no one wants to let Marketing down on the first day—you don’t want to be on their bad side! So let’s see what we’re working with here...

image with no caption

You could, but things might get messy.

Before we can use jQuery to make the cool effects that Marketing wants, we need to make sure that jQuery has everything in place to work its magic. As you already know now, one of jQuery’s main jobs is to manipulate HTML elements, so we need to have good structure. To get at elements, jQuery uses the same selectors that CSS uses, so we also need to have well-defined styles.

Revisit your requirements

When you’re thinking about your structure, it’s always good to go back to what you’re trying to build. Marketing wants an image to slide down and fade in when people click on the “Show Me the Furry Friend of the Day” section of the page. What changes to the HTML and CSS might you need to make?

image with no caption

Set up your HTML and CSS files

Let’s think about what we’ll have to set up in our HTML and CSS files before you write any jQuery statements. Open up the jQuery files for Chapter 1 (if you haven’t done that yet, be sure to go back to the opening section How to use this book: Intro for details). Find the Begin folder in Chapter 1. Then, add the code in bold below to the files, as shown here.

Do this!

image with no caption
image with no caption
image with no caption

You’re right. Our HTML and CSS are ready; now we need some jQuery.

We want the picframe div to slide and to fade. Fortunately, the jQuery folks have built effects that let us control both of these rich visual actions: slides and fades. We’ve devoted a whole chapter later in the book to jQuery effects (Chapter 5), so don’t worry about getting every little thing down now. Let’s just start sliding and fading first.

Slide on in...

The first effect we’ll implement is having the image slide into view, which is one of the things the marketing team manager wants to have happen. There are three ways to deal with sliding:

image with no caption
image with no caption
image with no caption

May the fade be with you

We also want the image to gradually appear, going from invisible to fully visible. Again, jQuery has a method for that, and that method is called a fade. The fade methods are pretty similar to what you just saw for sliding: you have FadeIn, FadeOut, FadeTo, and FadeToggle. For now, let’s just use FadeIn, which gives us control over the opacity and transparency properties of HTML elements.

image with no caption

Brain Power

How many jQuery statements do you think it will take us to accomplish the effect we want?

Take a shot at writing those statements on a piece of scratch paper. If you’re not sure, try to write it out first in plain English; then you’ll start getting your brain to think in jQuery.

That’s it?

Amazingly, you only need to write two lines of jQuery code to get these effects to work. Now you’re probably beginning to get a sense of why so many people like jQuery. Add the bolded lines below to your index.html file, and you’re good to go.

Do this!

image with no caption

Watch it!

Check it across multiple browsers.

Just because jQuery will work the same across all browsers doesn’t mean the styles you define in your CSS file, or any dynamic styles you apply to elements in your page, will react the same in all browsers!

You rescued the Furry Friends campaign

You got the job done with some HTML and CSS fine-tuning, and just two lines of jQuery. Just think of all the puppies you’ve saved...

image with no caption
image with no caption

Your jQuery Toolbox

You’ve got Chapter 1 under your belt and now you’ve added the basic jQuery function, selectors, click events, and the fade effect to your toolbox.

jQuery function

You use this to select elements from an HTML page to manipulate.

The $ shortcut means you don’t have to type “jQuery” over and over.

The jQuery function can handle selectors, straight HTML, and even JavaScript objects.


jQuery selects elements the same way CSS does: with selectors.

Just about any kind of HTML element is fair game for a jQuery selector.

Fade effect

Once you’ve selected an element, you can fade it in a variety of ways, using FadeIn, FadeOut, FadeTo, and FadeToggle.

You can fade in all kinds of elements, from text to images and more.

Control the speed of your fade effect by putting a time (in milliseconds) value inside the parentheses at the end of the statement.

The best content for your career. Discover unlimited learning on demand for around $1/day.