File Under: Frameworks, JavaScript

Get Started With JQuery

Programming with JavaScript used to be hard. Just look at all the JavaScript tutorials written by our Webmonkeys. Over the years we’ve done what we can to help you make sense of JavaScript.

Now we’re being helped out by JavaScript frameworks, like JQuery, Prototype and Moo Tools. These web frameworks sit on top of JavaScript and make some common tasks a whole lot easier. When you write in JQuery, as you will in this tutorial, you’re still writing JavaScript, but what used to be 50 lines may now be one or two. JQuery’s slogan is “write less, do more,” and it lives up to that promise.

In this tutorial, I’ll introduce you to a new way to write JavaScript: the easy, JQuery way. We’ll retrieve multiple objects in a single line, add CSS classes and make things magically disappear. At the end, you’ll be able to create an expandable Frequently Asked Questions template, where users can click a question and the answer will appear below.

You don’t have to be a pro to master JQuery (although going through Webmonkey’s JavaScript tutorials helps). Even if you’re new to JavaScript, you’ll want to read on and see what JQuery can do for you.

Contents

  1. What you’ll need
  2. Your Basic HTML Sets the Stage
  3. You Can Get Anything With JQuery
    1. Get An Object By ID
    2. Get Objects By Class
    3. Get Objects By Tag
    4. Filtering Objects
  4. Change Things Up With JQuery
    1. Change CSS Classes
    2. Change An Object’s Inner Text
    3. Change Your Appearances: Show and Hide
  5. Create An Expandable FAQ With JQuery
    1. Set Up The HTML
    2. JQuery’s “onLoad: the ready()” Function
    3. Make Your Questions Clickable
    4. Add “Expand All” Option to FAQ
  6. Become a JQuery Master

What you’ll need

  • Good understanding of HTML and CSS
  • Very basic knowledge of JavaScript
  • Willingness to have your mind blown away


Your Basic HTML Sets the Stage

You should be excited to write some JQuery. I know I am. First, we have to get the HTML ready to go. Copy the code below into an empty document:

<html>

<head>



	<title>Testing JQuery</title>

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

	<style>

		// CSS goes here

	</style>

	<script>



		// JavaScript goes here

	</script>

</head>

<body>



</body>

</html>

Opened in a browser, the above is blank. That’s because it’s only a starting place for the code we’ll be adding into it.

Before we start writing code, I want to point out something interesting about one of the script tags. The one above the style tag and below the title tag calls to an external JavaScript file. That’s normal, but the URL where the src leads is not.

Most shared JavaScript code requires you to download it and put it on your server. You can do that with JQuery if you want (download JQuery, if you’d like). However, you can piggyback off of Google’s servers by accessing the version stored on the Google Ajax APIs site, like we did in the example above.

Another note about scripts. The code we create in this tutorial will be written within one main HTML file. Normally, we’d link to an external JavaScript file instead. The same goes for our CSS, which we’ll put between the style tags. I’m including scripts and styles inline because I want to make the code easy to read and manipulate.

Before we move on to the code, let’s set up the HTML and CSS we’ll be using in the next section.

Add this between the body tags:

<div id="container">

<span>SPAN<br />No id</br />No class</span>



<span class="test" id="second">SPAN<br />id="second"<br />class "test"</span>

<div class="test">DIV<br />No id<br />class "test"</div>

</div>



<p>

<strong>Toggles:</strong>

</p>

And put this between the style tags:

#container div, #container span

{

	width: 150px;

	height: 150px;

	display: block;

	float: left;

	border: 1px solid black;

}

#container .highlight

{

	border: 3px solid orange;

}

p

{

	clear: left;

}

p input

{

	display: block;

}

Reload the HTML file you created and you’ll see a few squares on your screen. Yay! Now let’s JQuery-ify the sucker.

You Can Get Anything With JQuery

One of the best features of JQuery is its tools for grabbing objects from a page. Most of this happens through the dollar sign function, with CSS-like commands. In this section, I’ll show some of the common ways of selecting objects, as well as filtering a list of objects down to just the few you want.

To follow along, you can download the basic HTML file or copy and paste it from Webmonkey’s code library. I’ll also give you the code to add to this starting template at each step. By the end of this tutorial, you should have written a decent JQuery-powered expandable FAQ template.


Get An Object By ID

Identifying a single object by ID is similar to setting styles in CSS. Use the dollar sign function and pass the ID with a pound sign in front of it. Like this: $("#second")

To test this out in our example HTML file, add the following underneath the “toggles” section near the bottom of the HTML:

<input type="button" onClick="javascript:test_byid();" value="id='second'" />

This line adds a button to the page that, when clicked, calls the test_byid() function. Where is that function? We need to add it between the script tags in your example HTML file:

function test_byid()

{

	$("#second").toggleClass("highlight");

}

Reload the file and click the new button. The second span (the one with id="second") highlights.


Get Objects By Class

Grabbing all objects of a certain class also uses similar CSS commands and the dollar sign function. Check it: $(".test")

Let’s test it in our example HTML file. Here’s the code for the testing button:

<input type="button" onClick="javascript:test_byclass();" value="class='test'" />

And now the JavaScript, which you should paste below the previous function:

function test_byclass()

{

	$(".test").toggleClass("highlight");

}

Reload the file and click the new button. The two right boxes (the ones with class=”test”) highlight.


Get Objects By Tag

If you want all objects of a particular tag, you just need to pass the name of the tag to the dollar sign function. This is also similar to CSS: $("span")

In our example HTML file, paste this code for the button to test getting objects by tag:

<input type="button" onClick="javascript:test_bytag();" value="tag is 'span'" />

And the JavaScript function:

function test_bytag()

{

	$("span").toggleClass("highlight");

}

Reload and click the new button, you’ll see the two left boxes (the ones that are span tags) highlight.


Filtering Objects

JQuery has a whole lot of filters for finding only the items you want from a selection. We’ll filter the final example from the previous section, where we retrieved all the span tags.

Here’s the HTML for the two filtering buttons:

<input type="button" onClick="test_byfirstfilter();" value="the first object where tag is 'span'" />

<input type="button" onClick="test_bynotfilter();" value="tag is 'span', but id is not 'second'" />

And the script for both of these filters:

function test_byfirstfilter()

{

	$("span:first").toggleClass("highlight");

}

function test_bynotfilter()

{

	$("span:not(#second)").toggleClass("highlight");

}

Filters all start with a colon. In these examples, we use the :first and :not filters.

The :first filter returns only the first item in the collection. Where $("span") will return all the span tag objects, $("span:first") will return only the first span.

Click the first of our two new buttons and we’ll see the first span highlights. Success!

The second filter shows how to remove specific rules from being selected. This filter accepts a second set of CSS commands inside parentheses. The full JQuery command, $("span:not(#second)") will first grab all the spans, but then filter out any that have id="second".

Click the second of our two new buttons and we’ll see the first span highlights again. It is the only span that does not contain the “second” id.

If you’ve been following along, your web page should now look something like this:

You can get quite a bit more complicated with the JQuery filters. There is a whole list of filters on the JQuery site. See how to select every other element (i.e., for zebra striped tables), elements containing specific text, and more.

Or, if you’re all filtered out, move on to the next section. I’ll show you how to actually /do something/ with the objects we’re selecting with JQuery.

Change Things Up With JQuery

So far we’ve just selected objects on the page using JQuery. Now it’s time to do something with them. For this section, I’m removing all my previous HTML buttons and script from my file. You can work on the same one, or also clean house a bit. Or, like before, you can follow along with ****[advanced.html this section's examples]**** in one file.

There is an aspect to what I’ve shown so far that you’ve probably noticed: highlighting. It’s an example of what can be done with the results from a JQuery call. The first item below shows how it’s done, then I’ll get into some other ways to manipulate the objects on the page using JQuery.


Change CSS Classes

To alter the design of a site as a user interacts with it, you most likely want to add or remove CSS classes. JQuery makes it easy. In fact, every example so far has toggled the “highlight” class, which puts a 3 pixel orange border around our example boxes.

Add this HTML button to your file:

<input type="button" onClick="test_changeclass();" value="Change CSS class of id='second'" />

And this script:

function test_changeclass()

{

	$("#second").toggleClass("highlight");

}

The code is actually the same as the example to retrieve a particular ID. Here, we use the toggleClass function to tell JQuery which class to either add or remove. If the class is already there, it removes. Otherwise, it adds.

We can also change the toggleClass function to be addClass or removeClass to perform those functions directly.


Change An Object’s Inner Text

So far we’ve just made changes to how something looks. How about bigger changes? In this example, we’ll change the text inside some of the boxes using JQuery.

To do this, we’ll use the text function. It takes a string of text as an argument, where we tell it the new text to use.

Here’s the HTML code for our button:

<input type="button" onClick="test_changetext();" value="Change text where class='test'" />

And the script:

function test_changetext()

{

	$(".test").text("over-riding text for these boxes");

}

We use JQuery to return all the objects from the page with class “test”, then replace their inner text with the new text.

Reload your file, click the new button, and suddenly your right two boxes (the ones with class="test") will have new content inside.

The important thing to notice here is that JQuery made the change over multiple objects, but only required one line. If there had been 50 objects with class test, the code would have been the same. No looping code needed. JQuery does the hard work for us.

You’re probably beginning to see the real power of JQuery. In the next section, I’ll start making stuff disappear. Then you’ll /know/ it’s magic.


Change Your Appearances: Show and Hide

Now for some real fun. We’re going to make boxes disappear. To do this, we’ll need the hide function. Let’s get straight to the code, first for the button:

<input type="button" onClick="test_hiding();" value="Hide where id='second'" />

And then the script:

function test_hiding()

{

	$("#second").hide();

}

Reload the page, click the new button, and just like that, the box goes away. As you may have guessed, to get it to return, you’ll need to call $("#second").show(). Instead, let’s try toggling, since it may be a more popular method than using show and hide independently.

The idea behind a show/hide toggle is that if an object is currently displayed on the page, it will disappear. If it’s invisible, it will reappear. Voila!

Here is the button code:

<input type="button" onClick="test_hidetoggling();" value="Toggle show/hide where id='second'" />

And the script:

function test_hidetoggling()

{

	$("#second").toggle();

}

If you’ve been following along, the end result should look something like this:

Notice the code is virtually the same as the show code? Instead of calling the show function, we call the toggle function. All the work to determine whether something is viewable is done by JQuery.

This example of toggling viewability will come in handy for the next section. I’m going to show you how to create an FAQ that only shows the questions until you click to expand the answers.


Create An Expandable FAQ With JQuery

In this section, I’ll show an example project that you can start using in the real world right away. We’ll create an FAQ with questions and answers, then use JQuery to hide the answers and display one when the question is clicked.

You can follow along piece by piece or download the file or copy and paste it from the code library.

Set Up The HTML

Start with the shell of an HTML file, like in previous examples. Then add this definition list between the body tags:

<dl>

	<dt>Question number one</dt>

	<dd>Answer to first question</dd>



	<dt>Question number two</dt>



	<dd>Answer to second question</dd>



	<dt>Question number three</dt>

	<dd>Answer to third question</dd>

</dl>



A definition list (<dl> tag) is a semantic way to show questions and answers. JQuery doesn’t require this, but this simple markup does make things easier. Inside the definition list, we have questions as definition terms (<dt> tags) and the answers as definition descriptions (<dd> tags).


JQuery’s “onLoad: the ready()” Function

When the FAQ page is first loaded, we want the definitions to be hidden, so that only the questions are viewable. To do this, we need to call some JavaScript when the page first loads. JQuery provides a ready() function to make this easy.

Between the script tags near the top of your code, add this JavaScript:

$(document).ready(function(){

	$("dd").hide();

});

When the document is loaded, the browser will run an anonymous function. That function is declared inside the ready function. If you haven’t seen this before, it may look strange, but it’s part of the power of JavaScript and JQuery.

Inside the new function, we currently have one call, which may look familiar from previous sections of this tutorial. We are using JQuery to retrieve all the dd tags, then we’re calling the hide() function to make them disappear temporarily.

Reload your HTML file and you should now only see the questions list.


Make Your Questions Clickable

Now that we have successfully hidden the FAQ answers, we want to allow users to click questions in order to display the appropriate answer. In order to do this, we need to use JQuery to tell the browser that every dt tag can be clicked, then also tell the browser what to do when it’s clicked.

Add this code to your ready() function, just below the hide command from the previous section:

$("dt").click(function(){

	$(this).next().toggle();

});

Here we grab every dt tag, then run the click command, which attaches an event to the dt. Inside the click event, we create an anonymous function (similar to our ready() function) to toggle the visibility of the answer within the dd tag.

You may be asking, where do we reference the dd tag? We don’t. We let the power of JQuery and our semantic code do the work:

  1. Reference the object that was clicked with $(this)
  2. Call the next() function on the clicked object to return the object that comes after it in our HTML code. In this case, that is our dd tag.
  3. Toggle the visability of the dd tag.

Now, with very little JavaScript code, we’ve created an expandable FAQ that you could implement today. An added bonus is that this code has easy upkeep. Add or remove questions to the list and it still works without needing to edit any JavaScript code.

You could stop here, or you could add one more enhancement to the FAQ: the “expand all” link.


Add “Expand All” Option to FAQ

Some people hate expandable FAQs. These people may be no fun at parties, but that doesn’t mean we should deprive them of reading your Q&A. Let’s provide a one click option to show all the answers.

Above your definition list (dl), add a simple hyperlink:

<a href="#" onclick="showall();" id="linkshowall">Expand all</a>

Though there’s nothing but a pound sign as the URL for this link, the onclick event calls a function called showall(). Let’s create that function and use a simple JQuery statement:

function showall()

{

	$("dd").show();

}

You may notice that the call to show all the definition descriptions (dd) is similar to hiding. Yet, instead of calling the hide() function, we call the show() function.

The end result should look like this:


Now you’ve appeased the expandable FAQ haters and learned a tiny bit more JQuery. Where else can you go from here? Read on in the final section.


Become a JQuery Master

If you’ve made it this far in the tutorial, you have a good idea of the power JQuery has, while being easy to write. Hopefully you’re looking to learn even more JQuery and maybe even to become a JQuery master.

The JQuery docs are a little difficult to browse around, but are a good reference. Now you have a little knowledge of the way JQuery is written, you may be able to figure out how to use more advanced functions and filters. Just about every item in the docs has an example if you click through to the detail page.

Here are a few particular JQuery docs to check out: