You might have heard quite a lot about jQuery over the past couple of years—it's quickly become one of the most popular code packages in use on the Web today. And you might have wondered what all the fuss was about.
Whether you've tried to figure out JavaScript before and have thrown up your hands in frustration or have been too intimidated to even give it a go, you'll find that jQuery is a wonderfully approachable and relatively easy to learn approach to getting your feet wet with JavaScript.
In this chapter, we will cover:
What jQuery is and why it's ideal for designers
Progressive enhancement and graceful degradation
JavaScript basics
Downloading jQuery
Your first jQuery script
jQuery is a JavaScript library. That means that it's a collection of reusable JavaScript code that accomplishes common tasks—web developers often find themselves solving the same problems over and over again. Instead of engineering a solution from scratch each time, it makes sense to collect up all those useful bits into a single package that can be included and used in any project. The creators of jQuery have written code to smoothly and easily handle the most common and most tedious tasks we want to accomplish with JavaScript—and they've ironed out all the little differences that need to be worked out to get the code working in different browsers.
It's important to remember that jQuery is JavaScript, not a language of its own. It has all the same rules and is written the same way as JavaScript. Don't let that frighten you away—jQuery really does make writing JavaScript much easier.
jQuery's official tag line is Write Less, Do More. That's an excellent and accurate description of the jQuery library—you really can accomplish amazing things in just a few lines of code. My own unofficial tag line for jQuery is Find Stuff and Do Stuff To It because finding and manipulating different parts of an HTML document is extremely tedious with raw JavaScript and requires lines and lines of code. jQuery makes that same task painless and quick. Thanks to jQuery, you can not only quickly create a drop-down menu—you can create one that's animated and works smoothly in many different browsers.
So just what is it about jQuery that makes it so easy to learn, even if you have limited or no experience with JavaScript?
The first thing you'll often do in a jQuery script is select the elements you'd like to work with. For example, if you're adding some effects to a navigation menu, you'll start by selecting the items in the navigation menu. The tools you use for this job are selectors—ways to select certain elements on the page you want to work with.
jQuery borrowed selectors from CSS all the way up through CSS3 and they work even in browsers that don't support CSS3 selectors just yet.
Even though CSS offers a pretty robust set of selectors, jQuery adds a few more, all on its own, to make just the elements you need easy to work with.
If you already know how to do things such as make all the level 1 headings blue or make all the links green and underlined, then you'll easily learn how to select the elements you'd like to modify with jQuery.
If you want to create new elements or modify existing elements with raw JavaScript, you better crack your knuckles and get ready to write lots and lots of code—and it won't make all that much sense, either.
For example, if we wanted to append a paragraph to our page that said This page is powered by JavaScript, we would have to first create the paragraph element, then assign the text that should be inside the paragraph to a variable as a string, and finally append the string to the newly created paragraph as a text node. And after all that, we would still have to append the paragraph to the document. Phew! (Don't worry if you didn't understand all of that—it was just to illustrate how much work and code is required to do something this simple.)
With jQuery, adding a paragraph to the bottom of our page is as simple as:
$('body').append('<p>This page is powered by jQuery.</p>');
That's right—you just append a bit of HTML directly to the body and you're all set. I bet that without understanding JavaScript at all, you can read that line of code and grasp what it's doing. This code is appending a paragraph that reads This page is powered by jQuery to the body of my HTML document.
You've got better things to do than to sit and write lines and lines of code to add fade in and fade out effects. jQuery provides you with a few basic animations and the power to create your own custom animations right out of the box. Let's say I wanted to make an image fade into the page:
$('img').fadeIn();
Yep, that's it—one little line of code in which I select my image and then tell it to fade in. We'll see later in the chapter exactly where this line of code will go in your HTML page.
As I've said earlier, web developers often find themselves solving the same problems over and over again. You're likely not the first person who wanted to build a rotating image slideshow, an animated drop-down menu, or a news ticker.
jQuery has an impressively large library of scripts available freely—scripts to create tooltips, slideshows, news tickers, drop-down menus, date pickers, character counters, and on and on. You don't need to learn how to build all these things from scratch—you just have to learn how to harness the power of plugins. We'll be covering some of the most popular jQuery plugins in this book, and you'll be able to take what you've learned to use any plugin in the jQuery plugin library.
jQuery is an open source project—that means it's being collectively built by a team of super-smart JavaScript coders and is freely available for anyone to use. The success or failure of an open source project often depends on the community behind the project—and jQuery has a large and active community supporting it.
That means that jQuery itself is being constantly improved and updated. And on top of that, there are thousands of developers out there creating new plugins, adding features to existing plugins, and offering up support and advice to newcomers—you'll find new tutorials, blog posts and podcasts on a daily basis for just about anything you want to learn.
In this section, I am going to cover a few basics of JavaScript that will make things go more smoothly. We're going to look at a little bit of code and work through how it works. Don't be intimidated—this will be quick and painless and then we'll be ready to get on with actually doing something with jQuery.
There are a few different schools of thought when it comes to enhancing your HTML pages with JavaScript. Let's talk about some of the things we should consider before we dive into the cool stuff.
Progressive enhancement and graceful degradation are essentially two sides of the same coin. They both mean that our page with its impressive JavaScript animations and special effects will still work for users who have less capable browsers or devices. Graceful degradation means that we create our special effect and then make sure it fails gracefully if JavaScript is not enabled. If we take the progressive enhancement approach, we'll first build out a bare bones version of our page that works for everyone, and then enhance it by adding on our JavaScript special effects. I tend to favor the progressive enhancement approach.
Why should we care about users who don't have JavaScript enabled? Well, one of the Web's biggest users—search engines—do not have JavaScript capabilities. When search engines are crawling and indexing your pages, they will not have access to any content that's being loaded into your pages by JavaScript. That's often referred to as dynamic content, and it won't be indexed or found by search engines if it can't be reached with JavaScript disabled.
We're also in an era where we can no longer count on users accessing the web pages we build with a conventional desktop or laptop computer. We're quick to think of smart phones and tablets as the next candidates, and while they are very popular, they still only account for a tiny fraction of Internet access.
People are accessing the Web from gaming consoles, e-book readers, Internet-enabled televisions, a huge variety of mobile devices, and probably hundreds of other ways. Not all of these devices are capable of executing JavaScript—some of them don't even have color screens! Your number one priority should be making sure that your content is available to anyone who asks for it, no matter what device they happen to be using.
To accomplish this task of making our content available to as wide an audience as possible, we have to think of our web pages in three separate and distinct layers: content, presentation, and behavior.
Content is the meat of our web page—it's the text or the audio or video that we're most interested in presenting on our page, so this is where we start.
Mark up your content with clean, simple HTML code. Use HTML elements the way they were intended to be used. Mark up headings with heading tags, paragraphs with paragraph tags, lists with list tags, and save tables for tabular data.
Browsers have built-in styles for these basic HTML tags—headings will be larger type and probably bolded. Lists will have bullets or numbers. It might not look very fancy, but it's readable and accessible to anyone.
The presentation layer is where we start to get fancy. This is where we introduce CSS and start applying our own styles to the content we've created. As we style our page, we might find that we have to go back into our HTML and add some new containers and markup to make things such as multi-column layouts possible, but we should still strive to keep our markup as simple and as straightforward as we can.
JavaScript is a powerful and complex language—you can work with it for 10 years and still have more to learn. But don't let that frighten you away, you don't have to know everything about it to be able to take advantage of what it has to offer. In fact, you just have to get down a few basics.
This section introduces some JavaScript basics and JavaScript syntax. Don't be scared away by that developer word—syntax. Syntax just means the rules for writing a language, much like we have rules of grammar for writing English.
Let's start with something simple:
var x = 5;
This is a sentence in JavaScript. In English, we end a sentence with a period or maybe a question mark or exclamation point. In JavaScript we end our sentences with a semicolon.
In this sentence, we're creating a variable, x
. A variable is just a container for holding something. In this case, x
is holding the number 5
.
We can do math with JavaScript like this:
var x = 5; var y = 2; var z = x + y;
Just like algebra, our variable z
is now holding the value of the number 7
for us.
But variables can hold things other than numbers. For example:
var text = 'A short phrase';
Here, we've named our variable text
and it's holding some alphabetical characters for us. This is called a string. A string is a set of alpha-numeric characters.
Objects might be the hardest thing for a newcomer to JavaScript to grasp, but that's often because we overthink it, convinced it has to be more complicated than it actually is.
An object is just what it sounds like—a thing, anything. Just like a car, a dog, or a coffee maker are objects.
Objects have properties and methods. A property is a characteristic of an object. For example—a dog could be tall or short, have pointy ears or floppy ears, and be brown or black, or white. All of these are properties of a dog. A method is something an object can do. For example a dog can run, bark, walk, and eat.
Let's take my dog, Magdelena von Barkington, as an example to see how we would deal with objects, properties, and methods in JavaScript:
var dog = Magdelena von Barkington;
Here I've created a variable dog
that I'm using as a container to hold my dog, mostly because I don't want to have to type out her full name each time I refer to her in my code. Now let's say I wanted to get my dog's color:
var color = dog.color;
I created a container called color
and I'm using it to hold my dog's color property—color
is now equal to my dog's color.
Now, I've trained my dog very well, and I would like her to roll over. Here's how I would tell her to roll over with JavaScript:
dog.rollOver();
rollOver
is a method—something that my dog can do. After my dog rolls over, I might like to reward her with a treat. Here's how my dog eats a treat with JavaScript:
dog.eat('bacon');
Wait, what's going on here? Let's take it one step at a time. We have dog, which we know is a container for my dog, Magdelena von Barkington. We have the eat
method, which we know is something that my dog can do. But my dog can't just eat—she has to eat something. We use the parentheses to say what it is that she is eating. In this case, my lucky dog is eating bacon. In JavaScript speak, we would say we were passing bacon to the eat method of the dog.
So you see, objects aren't so difficult—they're just things. Properties are like adjectives—they describe traits or characteristics of an object. Methods are like verbs—they describe actions that an object can do.
A function is a bit of reusable code that tells JavaScript to do something. For example:
function saySomething() { alert('Something!'); }
This function tells JavaScript to pop up an alert box that says Something!
. We always start a function with the word function
then we name our function. That's followed by a set of parentheses and a set of curly brackets. The lines of instruction go inside the curly brackets.
Now, my saySomething
function won't actually do anything until it's called, so I need to add a line of code to call my function:
function saySomething() { alert('Something!'); } saySomething();
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
You might wonder what those parentheses are for. Remember how we could pass things to a method by including them in parentheses?
dog.eat('bacon');
In this case, we passed bacon to say what the dog was eating. We can do much the same thing for functions. In fact, methods actually are functions—they're just functions specialized for describing what an object can do. Let's look at how we modify our saySomething
function so that we can pass text to it:
function saySomething(text) { alert(text); } saySomething('Hello there!');
In this case, when I wrote the saySomething
function, I just left a generic container in place. This is called a parameter—we'd say the saySomething
function takes a text parameter, since I've called my parameter text
. I chose the name text
because it's a short and handy descriptor of what we're passing in. We can pass in any bit of text to this function, so text
is an appropriate name. You can name your parameter anything you'd like—but you'll make your code easier to read and understand if you apply some commonsense rules when you're selecting names for your parameters. A parameter behaves very much like a variable—it's just a container for something.
We're ready to include the magic of jQuery into a project, but first we need to download it and figure out how to get it attached to an HTML page. Here, we'll walk through getting a sample HTML file started, and all the associated files and folders we'll need to work through a sample project set up. Once we're finished, you can use this as a template for all the future exercises in the book.
Earlier, I described the three layers of an HTML document—content, presentation, and behavior. Let's take a look at how we can set up our files for these three layers:
First, let's set up a folder on your hard drive to hold all of your work as you work through the lessons in this book. Find a good place on your hard drive and create a folder called
jQueryForDesigners
.Inside the folder, create a folder called
styles
. We'll use this folder to hold any CSS we create. Inside thestyles
folder, create an empty CSS file calledstyles.css
.The styles represent our presentation layer. We'll keep all of our styles in this file to keep them separate. Likewise, create a folder called
images
to hold any images we'll use.Next, create a folder called
scripts
to hold our JavaScript and jQuery code. Inside thescripts
folder, create an empty JavaScript file calledscripts.js
.The JavaScript we write here represents our behavior layer. We'll keep all of our JavaScript in this file to keep it separate from the other layers.
Now, inside the
jQueryForDesigners
folder, create a new HTML page—very basic as follows:<!DOCTYPE html> <html> <head> <title>Practice Page</title> </head> <body> <!-- Our content will go here --> </body> </html>
Save this file as
index.html
. The HTML file is our content layer—and arguably the most important layer; as it's likely the reason site visitors are coming to our website at all.Next, we'll attach the CSS and JavaScript files that we made to our HTML page. In the head section, add a line to include the CSS file:
<head> <title>Practice Page</title> <link rel="stylesheet" href="styles/styles.css"/> </head>
And then head down to the bottom of the HTML file, just before the closing
</body>
tag and include the JavaScript file:<script src="scripts/scripts.js"></scripts> </body> </html>
As these files are just empty placeholders, attaching them to your HTML page won't have any effect. But now we have a handy place to write our CSS and JavaScript when we're ready to dive into an exercise.
Note
Note that it's perfectly fine to self-close a
<link>
element, but a<script>
element always needs a separate closing</script>
tag. Without it, your JavaScript won't work.Here's what my folder looks like at this point:
Now we have to include jQuery in our page. Head over to http://jq uery.com and hit the Download(jQuery); button:
You'll notice you have two options under Choose Your Compression Level. You'll always want to check the Production checkbox. This is the version that's ready to use on a website. The Development version is for experienced JavaScript developers who want to edit the source code of the jQuery library.
Clicking on the Download button will open the production jQuery file in your browser window, and it looks a little bit scary, as follows:
Don't worry, you don't have to read it and you definitely don't have to understand it. Just go to your browser's file menu and choose Save Page As... or right-click on the page and select Save As and then save the file to your hard drive, inside the
scripts
folder we created. By default, the script will have the version number in the file name. I'm going to go ahead and rename the file tojquery.js
to keep things simple.Now we just have to include our jQuery script in our page, just like we included our empty JavaScript file. Go to the bottom of your practice HTML file, just before the
<script>
tag we created earlier and add a line to include jQuery:<script src="scripts/jquery.js"></script> <script src="scripts/scripts.js"></script> </body> </html>
You won't notice any changes to your HTML page—jQuery doesn't do anything on its own. It just makes its magic available for you to use.
There is nothing wrong with downloading and using your own copy of jQuery, but you do have another option available that can help to improve the performance of your websites. That's to use a CDN-hosted copy of jQuery.
In case you don't know, a CDN is a Content Delivery Network. The premise behind a CDN is that files download faster from the servers that are physically closer to a site visitor's location. So, for example, if you're in Los Angeles, California, a copy of jQuery that's on a server in Phoenix, Arizona will download faster than a copy that's on a server in New York City. To help this along, a CDN has a copy of the same file on lots of different servers all around the world. Each time a site visitor requests a file, the CDN smartly routes their request to the closest available server, helping to improve response times and overall site performance.
It won't make much of a difference for the relatively simple examples and pages that we'll build in this book, but for a public-facing website, using a CDN-hosted copy of jQuery can make a noticeable difference. There are a few options out there, but the most popular by far is Google's Ajax API CDN. You can get the information on the latest version available and the correct URL at http://code.google.com/apis/libraries/devguide.html#jquery.
If you would like to use the Google CDN-hosted version of jQuery in your files, it's as simple as adding the following line of code to your HTML file, instead of the line we used previously to include jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
No downloading the file, no saving your own copy, you can just point your <script>
tag directly at the copy of jQuery stored on Google's servers. Google will then take care of sending jQuery to your site visitors from the closest available server.
Not only that, but as Google's CDN is so popular, there's a good chance that your site visitor has already visited another site that's also using a Google CDN-hosted copy of jQuery and that they'll have
jQuery cached in their browser. That means that your site visitor won't have to download jQuery at all—it's already saved in their browser and available to be used. How's that for improving performance?
Set up your files and folders just like we did in the previous exercise. Inside the
<body>
of the HTML document, add a heading and a paragraph:<body> <h1>My First jQuery</h1> <p>Thanks to jQuery doing fancy JavaScript stuff is easy.</p> </body>
Feel free to create some CSS in the
styles.css
in the styles folder—style this however you would like.Next, open up that empty
scripts.js
file we created earlier and add this bit of script to the file:$(document).ready();
Let's take this statement one at a time—first a dollar sign? Really? What's that doing in JavaScript?
The $
here is just a variable—that's all. It's a container for the jQuery function. Remember how I said we might use a variable to save ourselves a few keystrokes? The clever writers of jQuery have provided the $
variable to save us from having to write out jQuery
every time we want to use it. This code does the same thing:
jQuery(document).ready();
Except it takes longer to type. jQuery uses the $
as its short name because it's unlikely that you'd call a variable $
on your own since it's an uncommon character. Using an uncommon character reduces the chance that there would be some sort of conflict between some other JavaScript being used on a page and the jQuery library.
So, in this case, we're passing document
to the jQuery or $
method, because we want to select our HTML document as the target of our code. When we call the jQuery function, we get a jQuery object. In JavaScript speak, we would say that the jQuery function returns a jQuery object. The jQuery object is what gives the jQuery library its power. The entire jQuery library exists to give the jQuery object lots of properties and methods that make our lives easier. We don't have to deal with lots of different sorts of objects—we just have to deal with the jQuery object.
The jQuery object has a method called ready()
. In this case, the ready method will be called when the document is loaded into the browser, and is ready for us to work with. So $(document).ready()
just means, "when the document is ready".
We need to tell jQuery what to do when the document is ready. As we want something to happen, we'll pass in a function as follows:
$(document).ready(function(){ // Our code will go here });
We'll write what's going to happen inside this function.
What about that line that starts with
//
? That's one way of writing a comment in JavaScript. A//
tells JavaScript to ignore everything else on that line because it's a comment. Adding comments to your JavaScript is a great way to help yourself keep track of what's happening on what line. It's also great for helping along other developers who might need to work on your code. It can even be great for helping yourself if you haven't looked at your own code in a few months.Next, we'll add what we want to happen as soon as the document is ready:
$(document).ready(function(){ $('body').append('<p>This paragraph was added with jQuery!</p>'); });
Our function is using the jQuery function again:
$('body')
Remember how I said that jQuery uses CSS selectors to find stuff? This is how we use those CSS selectors. In this case, I want the <body>
tag, so I'm going to pass 'body'
to the jQuery function. This returns the <body>
tag wrapped in a jQuery object. Handily, the jQuery object has an append()
method that lets me add something new to the page:
$('body').append();
All I have to do now is pass the append method the thing I want to add to the page. In quotes, I'll pass in a line of HTML that I'd like to add:
$('body').append('<p>This paragraph was added with jQuery!</p>');
And that's it! Now when I load my page in a browser, I'll see my heading followed by two paragraphs—jQuery will add the second paragraph as soon as the document is loaded in the browser:

In this chapter, you were introduced to the jQuery library and learned a few things about it. We covered a bit of JavaScript basics and then we learned how to set up our files and folders for the exercises in this book. Finally, we set up a simple HTML page that took advantage of jQuery to add some dynamic content. Now let's take a look at how we can make links more powerful with jQuery.