Home Web Development jQuery for Designers Beginner's Guide Second Edition

jQuery for Designers Beginner's Guide Second Edition

By Natalie Maclees
books-svg-icon Book
eBook $25.99 $17.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Designer, Meet jQuery
About this book
Publication date:
July 2014
Publisher
Packt
Pages
398
ISBN
9781783284535

 

Chapter 1. Designer, Meet jQuery

You might have heard quite a lot about jQuery over the past couple of years. It has 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 easy-to-understand way to get started with JavaScript.

In this chapter, we will cover the following topics:

  • What jQuery is and why it's ideal for designers

  • Progressive enhancement and graceful degradation

  • JavaScript basics

  • Downloading jQuery

  • Your first jQuery script

 

What is jQuery?


jQuery is a JavaScript library. This means that it's a collection of reusable JavaScript code that accomplishes common tasks. Since web developers often find themselves solving the same problems over and over again, it makes sense to collect useful bits of code 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 this frighten you away—jQuery really does make writing JavaScript much easier.

jQuery's official tagline is "write less, do more." This is an excellent and accurate description of the jQuery library—you can really accomplish amazing things in just a few lines of code. My own unofficial tagline 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, while jQuery makes that same task painless and quick. Thanks to jQuery, you can not only quickly create a drop-down menu but you can also create one that's animated and works smoothly in many different browsers.

 

Why is jQuery awesome for designers?


So what is it about jQuery that makes it so easy to learn, even if you have limited or no experience with JavaScript?

It uses CSS selectors you already know

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 of its own to make accessing just the elements you need easy.

If you already know how to do things with CSS, such as make all the first-level headings blue or make all the links green and underlined, you'll easily learn how to select the elements you'd like to modify with jQuery.

It uses HTML markup you already know

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 much sense either.

For example, if we wanted to append a paragraph to our page that says This page is powered by JavaScript, we need 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 this, we'd 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 it requires to do something simple.)

With jQuery, adding a paragraph to the bottom of our page is as simple as the following line of code:

$('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 the 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 the HTML document.

Impressive effects in just a few lines of code

You've got better things to do than 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, we wanted to make an image fade into the page; we will use the following code line for this:

$('img').fadeIn();

Yep, that's it! We use one little line of code in which I select the image and then tell it to fade in. Later in the chapter, you'll see exactly where this line of code will go in your HTML page.

Huge plugin library available

As I said earlier, web developers often find themselves solving the same problems over and over again. You're most likely not the first person who wants 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 apply what you've learned to use any plugin in the jQuery plugin library.

Great community support

jQuery is an open source project, which means that 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 that supports it.

This means that jQuery itself is being constantly improved and updated. And on top of that, there are thousands of developers out there who are creating new plugins, adding features to existing plugins, and offering 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.

 

JavaScript basics


In this section, we're 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 step 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.

Progressive enhancement and graceful degradation

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 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, some of the Web's biggest users and search engines have either no JavaScript capabilities or very limited JavaScript capabilities. When search engines are crawling and indexing your pages, they will not have access to all of the content and features that are being added to your pages by JavaScript. This is often referred to as dynamic content, and it can't be reliably 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 who access the web pages we build with a conventional desktop or laptop computer. We're quick to think of smartphones and tablets as the next candidates, and while they are very popular, they still account for a tiny fraction of Internet access. People are accessing the Web from gaming consoles, feature phones, e-book readers, internet-enabled televisions, a huge variety of mobile devices, and dozens of other ways. Not all of these devices are capable of executing JavaScript, and 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.

Gotta keep 'em separated

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

Content is the meat of our web page. It's the text or audio or video content that we're most interested in presenting on our page; so this is where we start.

Mark up your content with clean and 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 of a larger type and will probably look bold. Lists will have bullets or numbers. It might not look very fancy, but it's readable and accessible to anyone.

Presentation

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 code and add some new containers and markup to make things such as multicolumn layouts possible, but we should still strive to keep our markup as simple and as straightforward as we can.

Behavior

Once our page has all of our content properly marked up and is styled to look the way we like, we can think about adding in some interactive behavior. This is where JavaScript and jQuery come in. This layer includes animations, special effects, AJAX, and so on.

 

Designer, Meet JavaScript


JavaScript is a powerful and complex language. You can work with it for 10 years and still have more to learn. However, 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 to 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 to write English.

Variables

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 an exclamation mark. In JavaScript, we end our sentences with a semicolon.

In this sentence, we're creating a variable (var), x. A variable is just a container for holding something. In this case, x holds the number 5.

We can do math with JavaScript as shown in the following code snippet:

var x = 5;
var y = 2;
var z = x + y;

Just like algebra, our variable z now holds the value of the number 7 for us.

However, variables can also 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 alphanumeric characters.

Objects

Objects might be the hardest thing for a newcomer in 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 as a car, a dog, and 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 could 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'd deal with objects, properties, and methods in JavaScript:

var dog;

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'd like her to roll over. The following line of code shows how I'd tell her to roll over with JavaScript:

dog.rollOver();

The rollOver() method is something that my dog can do. After my dog rolls over, I might like to reward her with a treat. The following line of code shows 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. However, my dog can't just eat—she has to eat "something". We can use some extra code inside the parentheses to say what it is that she is eating. In JavaScript, we call the code inside the parentheses an argument. In this case, my lucky dog is eating bacon. So in JavaScript, we'd describe this bit of code by saying we are passing bacon to the eat() method of the dog object.

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.

Functions

A function is a bit of reusable code that tells JavaScript to do something. For example, have a look at the following code:

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 and then we name our function. This is 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, as follows:

function saySomething() {
  alert('Something!');
}
saySomething();

You might wonder what those parentheses are for. Do you remember how we could pass arguments to a method by including them in parentheses? We used the following line of code:

dog.eat('bacon');

In this case, we passed bacon to say what the dog was eating. We can do the same thing for functions. In fact, methods actually are functions; they're just functions that are specialized to describe what an object can do. Let's look at how we modify our saySomething() function so that we can pass text to it, as follows:

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. In JavaScript, we'd say the saySomething() function takes a text parameter, as 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 sensible rules when you're selecting names for your parameters. A parameter behaves very much like a variable—it's just a container for something.

 

Downloading jQuery and getting set up


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. Once we're finished, you can use these files as a template for all the future exercises in the book.

 

Time for action – downloading and attaching jQuery


Earlier, I described the three layers of an HTML document: content, presentation, and behavior. Let's take a look at how to set up our files in these three layers, as follows:

  1. 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.

  2. Create a folder called images in the jQueryForDesigners folder to hold any images we'll use.

  3. Next, create a folder called styles. We'll use this folder to hold any CSS files we create. Inside the styles folder, create an empty CSS file called styles.css.

    The styles represent our presentation layer. We'll keep all of our styles in this file to keep them separate.

    Tip

    There is a standard CSS style sheet that we'll start with for each exercise in this book, which applies some basic colors and typography. You'll find the CSS code that should be included with all examples in the sample code for the book.

  4. Next, create a folder called scripts to hold our JavaScript and jQuery code. Inside the scripts folder, create an empty JavaScript file called scripts.js.

    The JavaScript we write here represents our behavior layer. We'll keep all of our JavaScript in this folder to keep it separate from the other layers.

  5. Now, inside the jQueryForDesigners folder, create a new HTML page—very basic with the following code:

    <!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 is arguably the most important layer, as it's likely to be the reason site visitors are coming to our website at all.

  6. Next, we'll attach the CSS and JavaScript files that we created to our HTML page. In the head section, add a line of code to include the CSS file, as follows:

    <head>
      <title>Practice Page</title>
      <link rel="stylesheet" href="styles/styles.css"/>
    </head>

    Then, head down to the bottom of the HTML file, just before the closing </body> tag, and include the JavaScript file as follows:

      <script src="scripts/scripts.js"></script>
      </body>
    </html>

    As these files are just empty placeholders, attaching them to your HTML page won't have any effect. However, now, we have a place to write our CSS code and JavaScript that will come handy when we're ready to dive into an exercise.

    Note

    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.

    The following screenshot is what my folder looks like at this point:

  7. Now, we have to include jQuery in our page. Head over to http://jquery.com and hit the Download jQuery button.

    This will take you to the Download page where you'll see that you've got quite a few options to download jQuery these days.

    Note

    As of April 2013, you officially have two versions of jQuery to choose from. In developer speak, these versions are called branches. To easily understand which branch you should use, keep this rule in mind. The 2.x branch of jQuery no longer has support for Internet Explorer (IE) 6, 7, or 8. If you're working on a project that will need to work in these older versions of IE, then you'll need to work with the 1.x branch of jQuery. If you don't need to support these older versions of IE, then you can choose to work with the 2.x branch. All the code files in this book will use the 2.x branch, since my philosophy with web development is to look forward, not back. However, all of the code samples will work fine with either the 1.x branch or the 2.x branch of jQuery.

    Note that the jQuery team will be discontinuing support for IE6 and IE7, even in the 1.x branch, with the jQuery 1.12 release in 2014.

    On the Download page, in the section for your selected branch, you'll see several files available for download: a compressed version and an uncompressed version, a map file, and release notes. The only file we need to be concerned with is the compressed, production version.

    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.

  8. Clicking on the link for the compressed, production version of your selected branch of jQuery will open the production jQuery file in your browser window, and it looks a bit scary, as shown in the following screenshot:

  9. 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.... 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 filename. I'm going to go ahead and rename the file to jquery.js to keep things simple.

  10. 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, as follows:

      <script src="scripts/jquery.js"></script>
      <script type="text/javascript" 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.

What just happened?

We learned how to set up our files and folders to work through the practice exercises in this book. We also learned how to select and download the correction version of jQuery and get it attached to our HTML page. Now we're all set to start coding pages and adding jQuery magic to them.

Pop quiz – setting up a new project

Q1. Which of the following is the content layer of a project?

  1. HTML

  2. CSS

  3. JavaScript

 

Another option for using jQuery


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 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.

Note

There are several CDN-hosted copies of jQuery available. You can find out about these on jQuery's Download page (http://jquery.com/download/). Just scroll down to the section titled Using jQuery with a CDN to find all your current options.

If you'd 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 in the previous section to include jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.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. This 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?

 

Your first jQuery script


Alright, now that you understand a few basic things about JavaScript and know how to get your files and folders set up to build a sample exercise, let's build our first simple example page and make it do something fancy with jQuery.

 

Time for action – getting ready for jQuery


Perform the following steps to start with your first jQuery script:

  1. Set up your files and folders just like we did in the previous exercise. Inside the <body> tags of the HTML document, add a heading and a paragraph, as follows:

    <body>
    <div class="content">
      <h1>My First jQuery</h1>
      <p>Thanks to jQuery doing fancy JavaScript stuff is easy.</p>
    </div>
    </body>

    Feel free to add some CSS code to the styles.css file in the styles folder. Style this however you'd like.

  2. Next, open up that empty scripts.js file we created earlier and add this bit of script to the file:

    $(document).ready();

What just happened?

Let's take this statement one thing at a time—first, the dollar sign. Really? What's this 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. The following code does the same thing that the preceding script did:

jQuery(document).ready();

Except that it takes longer to type. jQuery uses the $ sign as its short name because it's unlikely that you'd call a variable $ on your own as it's an uncommon character. Using an uncommon character reduces the chance that there will 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 $) function 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, we'd 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. We can pass a function to the ready method to say what should happen. So $(document).ready() just indicates when the document is ready.

 

Adding a paragraph


Now, we're all set to do something when the document is ready, but what is it that we'll do? Let's add a new paragraph to our page.

 

Time for action – adding a new paragraph


Perform the following steps to add a new paragraph to our page:

  1. We need to tell jQuery what to do when the document is ready. Since we want something to happen, we'll pass in a function like this:

    $(document).ready(function(){
      // Our code will go here
    });

    We'll write what's going to happen inside this function.

    What about the line that starts with //? That's one way of writing a comment in JavaScript. The // sign 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.

  2. Next, we'll add what we want the function to do as soon as the document is ready:

    $(document).ready(function(){
      $('body').append('<p>This paragraph was added with jQuery!</p>');
    });

What just happened?

Our new function is using the jQuery function again, as follows:

$('body')

Remember I said that jQuery uses CSS selectors to find stuff? This is how we use those CSS selectors. In this case, we want the <body> tag, so we'll 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 us add something new to the page, as follows:

$('body').append();

All we have to do is call the append method and pass in the paragraph we want to add to the page. In quotes, pass a line of HTML:

$('body').append('<p>This paragraph was added with jQuery!</p>');

That's it! Now, when you load the page in a browser, you'll see the heading followed by two paragraphs—jQuery will add the second paragraph as soon as the document is loaded in the browser. The following screenshot shows the page loaded in the browser:

Have a go hero – adding more content

Try adding the following bit of HTML to the bottom of the document with jQuery:

<div><p>This was added with jQuery too!</p></div>

Style it with CSS so that it stands out.

 

Summary


In this chapter, you have been introduced to the jQuery library and have 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 by creating tabs and custom tooltips.

About the Author
  • Natalie Maclees

    contacted on 10 may '16 _______________ Natalie MacLees is the founder of Purple Pen Productions (purplepen.com), an interactive agency based in Los Angeles, California. She has been designing websites since 1997 and is a passionate advocate of both accessibility and usability. She loves teaching and sharing her knowledge, both in seminars and workshops and also with her clients. She discovered WordPress a few years ago as a flexible, extendable, and quick way to build robust websites that clients could manage on their own. She is the organizer of the Southern California WordPress Meetup Group. She is also a Google Analytics Qualified Individual.

    Browse publications by this author
Latest Reviews (4 reviews total)
Understandable, with real life examples
I ordered the book to supplement my learning for a web programming course. It was very useful as a reference and learning tool.
jQuery for Designers Beginner's Guide Second Edition
Unlock this book and the full library FREE for 7 days
Start now