Getting Started with jQuery

Find out how to start coding with the jQuery JavaScript library. Shows how to install jQuery, and explores jQuery objects and the jQuery() function. Example code included.

jQuery logoIn What Is jQuery?, you learned that jQuery is a JavaScript library that makes it easy to create feature-rich, JavaScript-enabled Web pages.

Now you're ready to try out jQuery. In this tutorial you'll learn how to download and install the jQuery library, you'll explore jQuery objects and the jQuery() function, and you'll create a simple example jQuery script that brings all the concepts together.

Let's get going!

Downloading and installing jQuery

The easiest way to download the latest version of jQuery is via the jQuery homepage. Download the production (minified) version unless you want to tinker with the jQuery code itself. The production version has a much smaller file size, which means faster page loads for your visitors.

Save the downloaded file to a folder your hard drive. The file will be called something like jquery-1.4.1.min.js. To make thing simple, rename the file to jquery.js.

To use jQuery within a Web page, first save the page in the same folder as your jquery.js file. Then open your Web page in a text editor and add the following code inside your page's head element:


 <script type="text/javascript" src="jquery.js"></script>

This loads the jQuery JavaScript file whenever the Web page is opened in a browser, and makes the jQuery library available to any JavaScript code within the page.

So how do you actually use jQuery? To do this, you first need to understand 2 important concepts:

  • jQuery objects, and
  • the jQuery() function.

Understanding jQuery objects

Most of the time, when you work with jQuery, you access methods and properties of jQuery objects.

A jQuery object typically contains one or more DOM elements that you want to manipulate in some way. These DOM elements usually represent elements in the current Web page, such as images and paragraphs. You can also create DOM elements on the fly by using the JavaScript DOM functions, or with jQuery itself.

To create jQuery objects, you usually call the jQuery() function, which is explained below.

A useful feature of most methods of the jQuery object is that they return the same jQuery object when called. This allows you to chain methods together, which means you can achieve powerful effects with just 1 line of JavaScript code. More on method chaining in later tutorials.

The jQuery() function

Most of the time when using jQuery, you begin by calling the jQuery() function, passing in 1 or more arguments:


jQuery( arguments );

When called, the jQuery() function returns a jQuery object:


var jQueryObject = jQuery( arguments );

To make life easy and save typing, the jQuery developers also let you use a dollar ($) symbol as an alias for the jQuery function name. So you can also call the jQuery() function like this:


$( arguments );

Since $ is the more common convention, I'll use $ when calling the jQuery() function from now on.

There are several different ways that you can call the jQuery() function. Here are the 2 techniques you'll probably use most often:

$( selector [, context ] )
This uses the selector string to select 1 or more elements in the page to work with. The element(s) are returned as a jQuery object. selector can be any CSS1, 2, or 3 selector, as well as various jQuery-specific selectors. The optional context argument lets you limit the search to children of a specific DOM node, instead of the entire page.
$( handler )
This lets you set an event handler function, handler, to be run once the current Web page has finished loading. This ensures that your code doesn't run until all the elements within the page are available to the code.

In the following sections you'll learn how to use these 2 techniques.

Selecting elements in the page to work on

As you saw above, a common way to work with jQuery is to call the jQuery() function with a selector string. This selects an element (or elements) in the page, and creates a jQuery object that references those elements. You can then call various methods of the jQuery object in order to do things to the selected elements (such as hide them, fade them in or out, move them around, and so on).

Selector strings use the same syntax as CSS selectors. jQuery supports all selectors from CSS1 through to CSS3, and you can use all these selectors with any browser that jQuery supports (even IE6!).

Here's a simple example that selects all paragraphs in the page that have a class of "intro":


var paras = $( 'p.intro' );

After running the above code, paras holds a jQuery object that references all p elements with a class of "intro". That's how easy it is to select elements to manipulate in jQuery!

Running code when the document is loaded

The other common use of the jQuery() function is to start running your JavaScript code once the page's DOM tree has loaded.

You may already be familiar with JavaScript's load event, which fires once the entire page — including images, frames, and other external resources — has loaded:


window.onload = handler;

The above code calls the handler function once the page, images, and all other resources have loaded.

This is all very well; however, usually your JavaScript code can start running as long as the page itself has loaded and the DOM tree (the tree of objects representing the elements in the page) has been constructed. You don't need to wait for all the images and other resources to load as well.

To this end, jQuery gives you a simple way to run your JavaScript once the DOM is ready, without waiting for external resources to load:


$( handler );

The above code runs the handler function once the DOM tree has been constructed, without waiting for all images and other resources to load. Usually, handler will be your main function that kicks off your script.

A simple jQuery example

Now that you've got to grips with jQuery objects and the jQuery() function, you can try out a simple example.

Save the following code as a file in the same folder as your jquery.js file. Call the file fade.html:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A Simple jQuery Example</title>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

$( init );

function init() {
  $('h1').fadeOut('slow');
  $('h1').fadeIn('slow');
}

</script>

</head>
<body>

<h1>Hi there!</h1>

</body>
</html>

Now open fade.html in your Web browser. You should see the text "Hi there!" fade out, then fade back in. Reload the page to see the effect again.

So how does the code work? Let's break it down.

First the jQuery library is loaded:


 <script type="text/javascript" src="jquery.js"></script>

Next the jQuery() function is called, passing in a function name (init). This causes the init() function to run as soon as the page's DOM is loaded:


$( init );

The init() function itself uses jQuery to fade all h1 headings in the Web page out, then in. Take a look at the first line of the function:


  $('h1').fadeOut('slow');
  • $('h1') calls the jQuery() function to select all h1 elements in the page. The function returns a jQuery object referencing these elements. In this example, there is only a single h1 element, but if you added more h1 headings to the page then they would all be selected.
  • .fadeOut('slow') takes the jQuery object returned by the function call in the step above, and calls the object's fadeOut() method. fadeOut() is a jQuery method that fades out the elements referenced by the object — in this case the h1 heading in the page. The code passes the argument 'slow' to the method to fade the element out slowly.

The next line of the function works the same way, except it calls the fadeIn() method to fade the h1 heading back in:


  $('h1').fadeIn('slow');

Notice how it's possible to create quite impressive effects with a single line of JavaScript code. Incidentally, you could write the init() function more explicitly like this:


function init() {
  var headings = $('h1');
  headings.fadeOut('slow');
  headings.fadeIn('slow');
}

Summary

In this tutorial you've learned how to start coding with jQuery. You've looked at:

  • How to download the jquery.js file and link to it in your pages.
  • jQuery objects, which are primarily used to reference DOM elements.
  • The jQuery() function, also known as $(). This function has many uses, including selecting elements, creating elements, and running another function once the document is loaded.
  • A simple example that shows how to select all h1 elements in a page, fade them out, then fade them back in.

This tutorial has only scratched the surface of jQuery. In future tutorials I'll introduce different, powerful ways to select elements, and show how to manipulate elements, create advanced effects, run Ajax queries, and lots more. Happy coding!

Follow Elated

Related articles

Responses to this article

14 responses (oldest first):

20-Feb-10 12:44
Have to say thanks, both your articles have been great but can you just explain the following for me:



<script type="text/javascript">

$( init );

function init() {
$('h1').fadeOut('slow');
$('h1').fadeIn('slow');
}

</script>


What is the purpose of the first line, does that state that the following is javascript?

Also could you add more functions to the [function init] part after the fadeOut fadeIn to [h1]? Also how would you set it to continually loop?

Also last thing, if I wanted to add more javascript to another object would I be able to add it into that segment or would I have to copy paste the whole thing and then link it to the right objects?

Sorry thats alot of questions but first time using javascript.
20-Feb-10 16:03
@sycomadness: Thanks for your kind words! jQuery can be quite a difficult topic to explain on a beginner level, and I wasn't sure if the articles might have been a bit hard to follow. It's good to know they're making sense!

"What is the purpose of the first line, does that state that the following is javascript?"

Yes, that's exactly right. Everything up to the closing </script> tag will be interpreted by the browser as JavaScript.

"Also could you add more functions to the [function init] part after the fadeOut fadeIn to [h1]?"

Yes, you can add any JavaScript you like. I'll cover more things you can do with jQuery in later tutorials.

"Also how would you set it to continually loop?"


$( init );

function init() {
var headings = $('h1');
headings.fadeOut('slow');
headings.fadeIn('slow', init);
}


"Also last thing, if I wanted to add more javascript to another object would I be able to add it into that segment or would I have to copy paste the whole thing and then link it to the right objects?"

Not sure what you mean by "object" and "segment". If you want to select more page elements in jQuery then just add another line of JavaScript. eg to fade out a paragraph with an ID of "mypara" you might add:


$('p#mypara').fadeOut('slow');


Hope that helps!

Cheers,
Matt
30-Jun-10 22:24
i just want to thank you for this tutorial. i am new to jQuery, and have been wanting to learn it for a while now. today i was finally able to buckle down and do a search for some tutorials on line and i must say that not even the official jQuery website was more detailed and thorough for a beginner such as myself who didn't even know where to start.

I noticed that most of the tutorial sites that I found seemed to 'assume' that the 'beginner' already knew the 'obvious', and made the sad mistake of jumping right into their explanation of jQuery.

What I love about your tutorial is that you start RIGHT AT THE BEGINNING! You explain the fact that 1)YOU HAVE TO DOWNLOAD jQuery AND ACTUALLY PUT IT INTO YOUR FOLDER WITH YOUR WEBPAGE.

Well, to some people that might 'seem' obvious, but to a novice, it's not. So thank you again, because that clarity alone saved me much searching on the internet to be able to understand how to begin.

...and as I continued the tutorial, it only became clearer and even more understandable. I certainly look forward to following Elated for ALL related tutorials, hopefully until I can perfect my skills with jQuery!!!!

It's refreshing to find a site that makes sense from the beginning to the end....VERY THOROUGH!
02-Jul-10 00:51
@jQuerynewby: Thanks so much for your kind feedback on the tutorial. It really made my day!

I do try to spell things out in my "absolute beginner" tutorials, as it's very easy to assume background knowledge that readers might not have. I'm glad it helped.

I hope you enjoy the rest of my series of jQuery articles. I'm constantly adding more articles to the list:

http://www.elated.com/articles/cat/jquery/

I'd love to hear your feedback on the other articles in the series too.

Thanks again
Matt
07-Jul-10 13:40
you're welcome. i will certainly check out your link because i look forward to learning more. i am in the process of redesigning/
developing my business website, and i need so much help in jQuery/javascript.

thank you again.
09-Jul-10 00:55
I'm just starting the article, but one thing I remember from reading my one prior tutorial on JQuery is that it's better to do a call to Google's jquery.js in your web page rather than put it in the same folder of your web page. It's supposed to be that if your visitors have been to any other site with JQuery already then it's not reloaded on your page... a slight timesaver. Is that right at all?

Thanks for this article and looking forward to the rest of the series!
Deborah
14-Jul-10 20:08
@DebG: Thanks for your comment! You're quite right that you can link to the jQuery library on Google's CDN (content delivery network) as an alternative to hosting the library yourself.

There are many advantages to the CDN route - here's a good article on the topic: http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/

There are also some potential advantages to hosting the library yourself. For example, you're not reliant on people being able to access Google to use your site - not a problem 99.9% of the time, but there may be issues on an internal network, for example. You can work around this problem with tricks like this: http://snipplr.com/view/28239/google-cdn-hosted-jquery-with-local-fallback/

Generally though, on a public-facing production site it makes sense to use a CDN if possible.

Cheers,
Matt
13-Sep-10 05:19
Thanks for this great introductory article, Matt.

I'm totally new to jQuery and I intend to go through all your JQuery articles here on Elated.

Thanks again.

Juzer
14-Sep-10 00:55
Thanks for your comment Juzer.

I hope you enjoy reading the rest of my jQuery tutorials. More to come soon!

Cheers,
Matt
29-Oct-10 07:15
I sort of stumbled in to your site while googling for a beginners tutorial on jquery. I have to confess that this particular article put me on the right track. Like somebody noted above, most tutorials assume you know where to begin. Please, thanks so much. I am going through the rest of the article and I'm hoping to find one that deals with the use of plugins. I am particularly interested in a tutorial that details the use of the form validation plugin "validation". Can you give any help on that. Thanks you.
01-Nov-10 01:23
@tob115: Thanks for your kind words - I'm glad you found the tutorial easy to follow.

I haven't yet written a tutorial on using jQuery plugins, but I'll look into that. Meanwhile, if you have any specific questions on using the Validation plugin, feel free to post a new topic in the forums:

http://www.elated.com/forums/authoring-and-programming/topic/new/

Thanks!
Matt
15-Dec-11 18:06
I'm a long-time C programmer migrating into web development, inheriting some previously-written code. I have read a bunch of your tutorials (pointed to you by a recommendation on StackOverflow) and have learned a lot! Thanks!

My question is this:

In the article, you point out that the $( handler ) function is launched once the DOM is loaded, which helped me find the entry point for the code I'm to maintain.

In our own handler function, I also found the following call:


$(document).ready( function ( ) {
...
} )


This struck me as odd, so I went looking for an explanation.

Other pages (like http://www.learningjquery.com/2006/09/introducing-document-ready ) suggest using $(document).ready() in the manner you suggest to use $( ), with no mention of $( ) at all.

Obviously, $( ) works (our code uses it), so can you explain the difference between the two approaches, please?

(Or, if you've already addressed this question somewhere I wasn't able to find in my search, link me to it?)
19-Dec-11 23:07
@CuriousMind: There's no difference:

http://api.jquery.com/ready/
20-Dec-11 14:20
Ah, then I think I have some refactoring to do.

Thanks!

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page