Jump to main content or area navigation.

Contact Us

EPAFiles: Web Design

Getting Started With jQuery

Note: EPA no longer updates this information, but it may be useful as a reference or resource.

EPA builds all web content in the Drupal WebCMS as of January 2013. All new microsites and resource directories will be created using Drupal WebCMS. There is still content on EPA's legacy servers and this content will be maintained there until it is transformed and moved into the Drupal WebCMS. This information on styles and look and feel only applies to the existing content using Template 4 or older versions of EPA's template. Information for building new content is found in the EPA Web Guide.

Using jQuery isn't difficult: it's actually considerably easier than writing your own JavaScript code. But it does take some practice.

By the end of this tutorial, we will have written a decent jQuery-powered expandable FAQ template.

What You'll Need

  • Good understanding of HTML and CSS
  • Very basic knowledge of JavaScript
  • Willingness to have your mind blown away (or not)
  1. Your Basic HTML Sets the Stage
  2. You Can Get Anything With jQuery
  3. Change Things Up With jQuery
  4. Create An Expandable FAQ With jQuery
  5. Become a jQuery Master

Your Basic HTML Sets the Stage

First, let's write some testing HTML. Copy the code below into an empty document:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Testing jQuery</title>
  <style>
  /* CSS goes here */
  </style>
</head>
<body>
  <!-- HTML goes here -->
  <!-- JS goes at end of body -->
  <script src="http://www.epa.gov/epafiles/js/third-party/jquery.js"></script>
  <script>
    // JavaScript goes here
  </script>
</body>
</html>

Opened in a browser, the above HTML doesn't show anything. That's because it's a starting place for the code we'll be adding into it.

Before we start writing code, here's something interesting about the script tags. They're at the bottom of the HTML document, just before the closing </body> tag. Weird? You bet. Good coding practice? You bet!

Also note that you can link to EPA's shared jQuery file. We've minimized and gzipped the file, so it's actually only 26 KB, instead of over 100 KB. You can and should piggyback off this file.

Another note about styles and scripts: the code we create in this tutorial will be written into one main HTML file. EPA's standard practice is to link to external CSS or JavaScript files, which you'll do for all production code. For this tutorial, we're including scripts and styles inline because we want to make the code easy to read and manipulate.

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

Add this between the body tags:

<div id="content">
  <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>

This HTML sets up two spans, one with the text, 'SPAN No id No class' and one with the text, 'SPAN id="second" class "test".' There's also a div with the text, 'DIV No id class "test"'. Below these two spans and the div are the words, "Toggles:".

To style this HTML, put the following between the style tags in the <head>:

#content div, #content span { border: 1px solid black; display: block; float: left; height: 150px; width: 150px; }
#content .highlight { border: 3px solid orange; }
p { clear: left; }
input { display: block; }

This CSS will style the spans and div into "boxes" sitting next to each other. Reload the HTML file you created and you'll see a few squares with some text on your screen. Yay! Now let's apply jQuery.

jQuery's "ready()" Function

Now, to use jQuery, you need the ready event. All jQuery code is placed inside the ready event so it is executed when the document is fully loaded (i.e., "ready"). jQuery provides a ready() function to make this easy.

Between the 2nd pair of script tags near the bottom of your HTML, add this JavaScript:

$(function(){
  // Your custom code goes here
});

When the document is loaded (view source to see your changes), the browser will run the ready function. If you haven't seen this before, it may look strange, but it's part of the power of jQuery.

Top of Page


You Can Get Anything With jQuery

One of the best features of jQuery is its ability to grab objects from a page. Most of this happens through the jQuery's "dollar sign" function, with CSS-like commands. In this section, we'll walk through common ways of selecting objects, as well as filtering a list of objects down to just the few you want.

You can read more about all the different types of selectors at jquery.com Exit EPA Disclaimer.

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 in our example HTML file, add the following button underneath the "Toggles" paragraph:

<input type="button" id="second-toggle" value="id='second'" />
code Note

click: if you click on the matched element, it triggers the click event and executes the function.

toggleClass: if a matched element already has the class, it is removed; if an element does not have the class, then it is added.

Add the following JS in between your ready function, underneath the // Your custom code goes here comment:

$(function(){
  // Your custom code goes here
  $('#second-toggle').click(
    function () {
      $('#second').toggleClass('highlight');
  });
});

Reload the file and click the button with the label "id='second'". The second span (the one with id="second") highlights. Click the button again, and the highlight around the span goes away.

To understand this bit of JS: we used jQuery to find the element with the id of second-toggle (the button). When you clicked on the button, jQuery triggered a function to toggle the class (highlight) on element with the id of second (the span).


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 the class button. Add it just below the button you created in the previous section:

<input type="button" id="test-toggle" value="class='test'" />

And now the JavaScript, which you should paste below the previous code and inside the ready function:

$('#test-toggle').click(
  function () {
    $('.test').toggleClass('highlight');
});

Reload the file and click the new button. The two right boxes (the ones with class="test") highlight. Click again, and the highlight goes away.

To understand this bit of JS: we used jQuery to find the element with the id of test-toggle (the button). When you clicked on the button, jQuery triggered a function to toggle the class (highlight) on the two elements (the 2nd span and the div) with a class of test.


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" id="span-toggle" value="tag is 'span'" />

And the JavaScript:

$('#span-toggle').click(
  function () {
    $('span').toggleClass('highlight');
});

Reload and click the new button, you'll see the two left boxes (the ones that are span tags) highlight. Click again, and the highlight goes away.

To understand this bit of JS: we used jQuery to find the element with the id of span-toggle (the button). When you clicked on the button, jQuery triggered a function to toggle the class (highlight) on the two spans.


Get Objects By Attribute

The 'attribute contains' selector $("a[href*=something]") will select all anchors with an href that contains the word 'something' like this: <a href="http://testsomething.com"></a>


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 Get Objects By Tag section, where we retrieved all the span tags.

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

Here's the HTML for the first filtering button:

<input type="button" id="filter-toggle01" value="the first object where tag is 'span'" />

And the script for the first filter:

$('#filter-toggle01').click(
  function () {
    $("span:first").toggleClass("highlight");
});

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 button labeled "the first object where tag is 'span'" and see it highlight. Success!

Here's the HTML for the second filtering button:

<input type="button" id="filter-toggle02" value="tag is 'span', but id is not 'second'" />

And the script for the second filter:

$('#filter-toggle02').click(
  function () {
    $("span:not(#second)").toggleClass("highlight");
});

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 rule, $("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 are a lot of different types of selectors at jquery.com Exit EPA Disclaimer. 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. We'll working how to actually do something with the objects we're selecting with jQuery.

Top of Page


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 clean house a bit.

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" id="test" value="Change CSS class of id='second'" />

And this script:

$('#test').click(
  function () {
    $("#second").toggleClass("highlight");
});

Here's the HTML. The code is actually the same as the example to retrieve a particular ID. Again, 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 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" id="text" value="Change text where class='test'" />
code Note

text: set the text contents of all matched elements.

And the script:

$('#text').click(
  function () {
    $(".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 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" id="hide" value="Hide where id='second'" />

And then the script:

code Note

hide: hides each of the set of matched elements if they are shown.

$('#hide').click(
  function () {
    $("#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" id="toggle" value="Toggle show/hide where id='second'" />

And the script:

$('#toggle').click(
  function () {
    $("#second").hide();
});

Reload your file, click the new button. 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.

Top of Page


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.

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>

(Here's the HTML.) 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).


Hide the Questions

When the FAQ page is first loaded, we want the definitions to be hidden, so that only the questions are viewable. Between the script tags, add this JavaScript:

$("dd").hide();

Don't forget your ready function.

We have one call, which will look familiar from previous sections of this tutorial. We are using jQuery to retrieve all the <dd> tags, then we call the hide() function to make them disappear.

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:

code Note

css: set style properties on all matched elements.

next: gets the unique next siblings of each of the given set of elements.

$("dt").css({ cursor: "pointer", color: "#4298aa" }).click(function(){
  $(this).next().toggle();
});

Here we grab every dt tag, change its CSS by applying a few styles, and then run the click command, which attaches an event to the dt. Inside the click event, we create a 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 (the <dt>) 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 dislike 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 link to show all the answers.

Now, because we're using JS to hide the answers, let's also use JS to create this one-click option. (Otherwise, for those with JS off, the "Expand All" button is useless!)

$("#content").prepend('<a href="#" id="show">Expand all</a>');
$("dd").hide();
$("dt").css({ cursor: "pointer", color: "#4298aa" }).click(function(){
  $(this).next().toggle();
});
$("#show").click(
  function () {
    $("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 made everyone happy and learned a tiny bit more jQuery.


A Slicker FAQ

Here's a slicker FAQ with some more jQuery.

Top of Page


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

For help with your epa.gov web design, contact the Web Template Workgroup.

Jump to main content.