corner imagecorner image
FeaturesPluginsDocs & SupportCommunityPartners

Using jQuery to Enhance the Appearance and Usability of a Structured Document

jQuery is a light-weight JavaScript library that allows programmers to easily and quickly add enhancements to the appearance and behaviors of their web pages. jQuery's syntax is concise and makes use of variables in the form of CSS selectors as a way of connecting an effect with any targeted element of the DOM, be it a unique element (id), or set of elements (class), or arbitrarily chosen. Because jQuery is JavaScript, it can be embedded in any project where JavaScript can be applied.

In addition to the basic effects provided by the core jQuery library, a wide array of jQuery plugins is available, offering many options for customization.

In this tutorial, we will get acquainted with jQuery. We will be introduced to key jQuery concepts, including the $(document).ready function call, the use of CSS-selector-like jQuery objects, and the chaining together of jQuery effects and behaviors. We will also get a sense of what's possible through jQuery enhancements to ordinary HTML and similar documents.

Then we will use the example of a "contacts list" document to demonstrate how a structured HTML document can be enhanced using jQuery. In particular, we will show how using the accordion visual effect can offer an easy-to-use, intuitive, and attractive interface for providing both a high-level view of all the data present, while allowing the user easy access to detailed information about any individual data node they care to select.

This document makes use of the NetBeans 6.5 release. To use an earlier version of NetBeans, simply acquire the jQuery libraries from their source and put them in your project manually.

Expected Duration: 45 minutes.

Contents

To follow this tutorial, you will need the following resources.

Software or Resource Version Required
NetBeans IDE 6.5 Java Web and EE or PHP pack
Java Development Kit (JDK) version 5 or higher

Note: Download the following zip archive and extract it to a convenient place. It contains the JavaScript and .jpg files neeeded to complete this tutorial. They are included within a completed working copy of this project, which can be used for reference as you progress through the tutorial.

Prerequisites

This document assumes you have some basic knowledge of, or programming experience with, the following technologies:

  • NetBeans IDE
  • JavaScript
  • CSS selectors and HTML tags

We will be using the NetBeans 6.5 IDE to create a plain HTML file, but in principle, these steps can be applied in any web document file format where JavaScript can be embedded, including JSP, PHP and others.

Note: Although we will be using the PHP-only build of NetBeans 6.5, this tutorial does not require the use of PHP itself. If you have a local web server configured for testing that is running PHP, then you can test the project from there. Even if you do not have a local web server, you can do the tutorial by simply saving the HTML file we will create and then viewing it in a web browser that has JavaScript enabled.

Setting Up a jQuery Project

  1. Start by creating a new project (Ctrl-Shift-N). Select File > New Project.

  2. In the window that appears, select PHP on the left, and then PHP Application on the right.

  3. Click Next.

  4. Give the project a name. We'll call ours jqproject.

  5. Select the directory where we'll save the project. Click Next.

  6. In the Run Configuration settings, select Local Web Site and then verify that the Project URL is correct for your configuration.

  7. Select Copy files from sources folder to another location, and then in Copy to Folder, select the directory you want to use on your local web server. In this case, the directory jqproject will be created for you in the directory you choose:

    Run Configuration

    Note: If you are not running a local web server, simply accept all the default values. Do not select Copy files from sources folder to another location. In this instance, it will be best simply to view the HTML file we will create in your browser directly from the NetBeans project folder.

  8. Click Finish. NetBeans creates the project and opens the file index.php.

    We will be working on a plain HTML document, so we can begin by deleting index.php and creating index.html to replace it. (This is for the benefit of those not running PHP on their local web server. If you are not one of those users, you can just go ahead and use 'index.php' to complete the tutorial, skipping the next four steps.)

  9. Right-click index.php and select Delete.

  10. Now right-click the Source Files node icon, and select New and then HTML File….

  11. For File Name: enter "index". Verify that the Project and Created file path are correct.

  12. Click Finish.

Load the page we just created in your web browser. If you are running a local web server, enter the URL of the project as configured above in the location bar of your browser. Otherwise, find the file index.html file in your NetBeans project directory, in the subdirectory jqproject and open it in your web browser. You should see a page similar to this:

Browser Test

Back in NetBeans, delete all the text in index.html and replace it with the following:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery test project</title>
<style type="text/css">

</style>
</head>
<body>

</body>
</html>

Note: Because recent browsers already support the doctype and charset declarations from the proposed HTML 5 specification, we are using them in this tutorial. An actual production-ready project may require that you use different and more explicit forms of the doctype and charset declarations, which might necessary to support older web browsers or to author pages in quirks mode. The HTML 5 doctype used here triggers standards mode in all recent browsers.

Before we can begin working with jQuery, we must add the jQuery library to the project. NetBeans 6.5 ships with the jQuery library included.

  1. Right-click on the main jqproject node at the root level of our project and select Properties. The Properties settings appear.

  2. Under Run Configuration, verify that index.html is set in the Index File setting (or index.php if you are continuing the tutorial using a PHP file.)

  3. Select JavaScript Libraries. Click the Add… button on the right.

    Project Properties Window

  4. Select jQuery 1.2.6.

    The default settings create a long and ungainly path to the library, so let's change it to something simpler.

  5. Click the button with to the right of the selection. A dialog box appears.

    Add Libraries

  6. Simply add /js to the end of the path and then click Open.

    Add Custom Path

  7. Verify that the path is correct and then click OK.

    In the Project Properties window, you will see that jQuery 1.2.6 has been added to the list of JavaScript Libraries.

  8. Click OK.

    Observe that the directory js has been added to our Source Files, and that jQuery-1.2.6.js is within it.

    Now we connect the jQuery library to our project by creating a link to the script in the index.html file.

  9. Enter the following immediately after the pair of <style> tags, right before the closing </head> tag:

    <script type="text/javascript" src="js/jquery-1.2.6.js"></script>
  10. Save.

The jQuery library is now included in our project, linked to our project file, and ready to use.

Warning: Early builds of NetBeans 6.5 have a bug where a project's JavaScript files are not properly moved to the "other location" specified in the setting above. The workaround is to copy the files manually to the correct location on the localhost. Keep this in mind throughout this tutorial, since we will be adding more JavaScript files to the project later.

Getting Acquainted with jQuery

jQuery works by connecting dynamically-applied JavaScript attributes and behaviors to elements of the DOM (Document Object Model). Let's add an element to the DOM and try to affect its properties. We'll create a heading that changes color from black to blue when we click on it.

We start by creating the heading, structurally an <h1> element. Enter the following between the <body> tags:

<h1>Test.</h1>

Now we'll create a CSS class that makes an element appear blue when it is applied. Enter the following between the <style> tags in the <head> of the document:

.blue { color: blue; }

Next we'll set up a place to put our jQuery commands. Add a new set of <script> tags to the <head> of the document, after the jQuery script tag, like these:

<script type="text/javascript">

</script>

The jQuery instructions that we will add must be executed only after all of the elements of the DOM have been loaded by the browser. This is important because jQuery behaviors connect to elements of the DOM, and these elements must be available to jQuery so that we get the results we expect. jQuery takes care of this for us through its built-in (document).ready function, which follows the jQuery object, represented by $. Enter this construction between the script tags you just created:

$(document).ready(function(){

});

Note: There is also an abbreviated version of this function, which you may use if you prefer, that looks like this:

$(function(){

});

Our instructions for jQuery take the form of a JavaScript method, with an optional object literal representing an array of parameters, and must be placed between the curly braces {} inside the (document).ready function in order to execute only at the proper time, which is after the DOM has completely loaded.

Our document should now look like this:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery test project</title>

<style type="text/css">
    .blue { color: blue; }
</style>

<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<script type="text/javascript">
    $(document).ready(function() {

    });
</script>

</head>
<body>
    <h1>Test.</h1>

</body>
</html>

To demonstrate how jQuery syntax works, let's try something simple. We will add jQuery instructions to our page that will make the word "Test" turn blue when we click on it. To accomplish this, we want jQuery to add the CSS class .blue to the <h1> element of the DOM when it receives a mouse click.

Enter the following code inside the (document).ready function, between the braces {}:

$("h1").click(function(){
	$(this).addClass("blue");
});

Save the document and load it in your web browser. Test it to see if it works. When you click on the word "Test", it should turn blue.

This example uses the jQuery click() function to invoke the jQuery addClass() function when an element matching the CSS selector "h1" is encountered. The $(this) refers back to the calling element. If we were to add more <h1>s to our page, the same behavior will be applied to all of them with this single set of rules, and each will interact with jQuery independently. (You can try this yourself as a quick exercise.)

Another important quality of jQuery is that functions can be simply chained together to create more complicated or even sequenced behaviors. To demonstrate this let's add a jQuery instruction for a slow fadeOut to our click() function. Place a fadeOut("slow") jQuery function after the addClass function so that the line of code looks like this:

$(this).addClass("blue").fadeOut("slow");

The complete jQuery function should now look like this:

$(document).ready(function(){
	$("h1").click(function(){
		$(this).addClass("blue").fadeOut("slow");
	});
});

Refresh the page and then click "Test." You will see that it turns blue, and then fades out, disappearing from the page. (To try it again, you must refresh the page.)

Applying jQuery Behaviors to a Structured Document

We created the simple test above by using JavaScript behaviors that are included in the base jQuery library. Now let's see what's possible when we add features through the use of jQuery plugins.

We will take the simple example of an employee contact list, create a structured document that reflects the relationships among the individual content items, and solve a number of presentation problems using CSS and jQuery. When we structure the document, we will use HTML markup appropriate to the semantic meaning of the document elements.

Clearly, an employee contact list is a list, and to reflect this we will use the <ul> (unordered list) and <li> (list item) elements to structure it. Further, each individual person on the list will have their own list of facts that uniquely pertain to them. From the perspective of semantics, therefore, what we have is a list of lists. Our document structure will reflect that with a series of unordered lists, each embedded in a list item, itself part of a single unordered list.

In addition, each list item will receive a CSS class that reflects its meaning. This gives us (and jQuery) the possibility of treating each individual item in a semantically appropriate way. In our contact list, each person is described by a collection of data about them: Each has a small portrait image, along with entries for their job title, office address, phone number, an obfuscated e-mail address, and a brief bio.

  1. Paste the following code into your document in place of <h1>Test.</h1>:

    <ul id="infolist">
    <li>
        <a class="personName" href="#">Mary Adams</a>
        <div class="person">
        <ul>
        <li class="portrait">
            <img src="pix/maryadams.jpg" alt="Mary Adams">
        </li>
        <li class="title">Vice President</li>
        <li class="office">102 Bldg 1</li>
        <li class="phone">4 8234</li>
        <li class="email">mary.adams(at)company.com</li>
        <li class="bio">
            Neque porro quisquam est, qui dolorem ipsumquia
            dolor sit amet, consectetur, adipisci velit, sed
            quia non numquam eius modi tempora incidunt ut
            labore et magnam aliquam quaerat voluptatem. Ut
            enim ad minima veniam, quis nostrum exercitationem
            ullam corporis suscipit laboriosam, nisi ut aliquid
            ex ea commodi consequatur? Quis autem vel eum iure
            reprehenderit qui in ea voluptate velit esse quam
            nihil molestiae consequatur, vel illum qui dolorem
            eum fugiat quo voluptas nulla pariatur?
        </li>
        </ul>
        </div>
    </li>
    
    <li>
        <a class="personName" href="#">John Matthews</a>
        <div class="person">
        <ul>
            <li class="portrait">
                <img src="pix/johnmatthews.jpg" alt="John Matthews">
            </li>
            <li class="title">Middle Manager</li>
            <li class="office">307 Bldg 1</li>
            <li class="phone">4 3082</li>
            <li class="email">john.matthews(at)company.com</li>
            <li class="bio">
                Sed ut perspiciatis unde omnis iste natus error sit
                voluptatem accusantium doloremque laudantium, totam
                rem aperiam, eaque ipsa quae ab illo inventore veritatis
                et quasi architecto beatae vitae dicta sunt explicabo. Nemo
                enim ipsam voluptatem quia voluptas sit aspernatur aut odit
                aut fugit, sed quia consequuntur magni dolores eos qui
                ratione voluptatem sequi nesciunt.
            </li>
        </ul>
        </div>
    </li>
    
    <li>
        <a class="personName" href="#">Sam Jackson</a>
        <div class="person">
        <ul>
            <li class="portrait">
                <img src="pix/samjackson.jpg" alt="Sam Jackson">
            </li>
            <li class="title">Deputy Assistant</li>
            <li class="office">457 Bldg 1</li>
            <li class="phone">4 3494</li>
            <li class="email">sam.jackson(at)company.com</li>
            <li class="bio">
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
                do eiusmod tempor incididunt ut labore et dolore magna aliqua.
                Ut enim ad minim veniam, quis nostrud exercitation ullamco
                laboris nisi ut aliquip ex ea commodo consequat.
            </li>
        </ul>
        </div>
    </li>
    
    <li>
        <a class="personName" href="#">Jenifer Applethwaite</a>
        <div class="person">
        <ul>
            <li class="portrait">
                <img src="pix/jeniferapplethwaite.jpg" alt="Jenifer Applethwaite">
            </li>
            <li class="title">Senior Technician</li>
            <li class="office">327 Bldg 1</li>
            <li class="phone">4 9430</li>
            <li class="email">jenifer.applethwaite(at)company.com</li>
            <li class="bio">
                Duis aute irure dolor in reprehenderit in voluptate velit esse
                cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
                cupidatat non proident, sunt in culpa qui officia deserunt
                mollit anim id est laborum.
            </li>
        </ul>
        </div>
        </li>
    </ul>

    Observe that the overall enclosing <ul> element is given an id attribute with a value of infolist. In this <ul> structure, each <li> element contains an anchor element <a> with a 'class' attribute holding the value of 'personName'. In addition, each embedded list of personal facts is contained by a <div> with the class attribute value of `person'. Further, each individual personal fact has a class attribute value that reflects its semantic meaning.

  2. Save the document.

  3. Now we will add the the .jpg portraits that are referenced in the above code fragment to our project. Retrieve the pix/ directory from the .zip archive you downloaded earlier and copy the entire directory to your project folder, placing it at the same level as index.html and the js/ directory. After a brief moment, NetBeans will automatically update the Projects window to reflect that a new directory has been manually added to the project.

  4. Switch to your browser, and refresh.

There are a number of problems with this document that we will address. Firstly, it is more difficult than it needs to be to scan the list quickly to find the person you're looking for: one must scroll the page and visually inspect a lot of information that may not be of immediate interest. Four contacts in a list might be manageable, but if the number grew to, say, 50, then the list would become much more difficult to use. Secondly, none of the information, save the headers, has any distinguishing typographical characteristics that suggest its purpose or relative importance to the other items on the pages. Thirdly, the document is visually plain, and is unlikely to blend in esthetically with most web site designs, particularly designs that have a strong graphic identity. We will address these issues by using the jQuery accordion object, in combination with a CSS stylesheet.

Adding a jQuery Plugin to the Project

The jQuery library that was added to our project at the start brings only a basic feature set to our project. Fortunately, it is easy to add new capabilities and features to our project by downloading and installing from a variety of jQuery plugins. These plugins are simply JavaScript files that are loaded along with jQuery when the web browser initializes the web page.

  1. To produce the accordion effect we want, we will start by adding two plugins to our project: ui.core.js and ui.accordion.js. You can retrieve them from the .zip archive you downloaded earlier, located in the js/ directory.

  2. Put these two files in the js/ directory we created earlier in your NetBeans project folder.

  3. Enter two <script> tags with references to these two new files into the head of the document, immediately after the the <script> tag that refers to the core jQuery library jquery-1.2.6.js. Use the existing <script> tag as a model.

  4. Delete the test code we created inside the (document).ready function. We no longer need it. Also delete the .blue style we created for testing purposes inside the <style> tag.

Our head tag should now look like this:

<head>
<meta charset="utf-8">
<title>jQuery test project</title>

<style type="text/css">

</style>

<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<script type="text/javascript" src="js/ui.core.js"></script>
<script type="text/javascript" src="js/ui.accordion.js"></script>

<script type="text/javascript">
	$(document).ready(function(){

	});
</script>

</head>

To make our static, unstyled list take on the accordion behavior is as simple as adding a single line of jQuery code. Enter this line into the (document).ready function:

$("#infolist").accordion();

In this line of code, #infolist is a CSS selector connected to a unique DOM element that has an id attribute with the value infolist; in other words, our contacts list. It is connected with a . to the jQuery instruction to use the accordion() method in displaying this element.

Go back to the web browser and refresh. Click on one of the names (other than the top one) to see the accordion effect in action. Not only does jQuery handle all the details of animating the DOM and responding to user mouse clicks, it also sees to it that all of the entries occupy the same vertical height. This sort of attention to detail is typical of jQuery, and reinforces the user's sense that the web application is well thought-out and professional.

Now we'll add one more bit of code that will make no apparent difference now, but will help us out later when we get to the final part of the tutorial. We will insert an object literal into the accordion() function that specifies the DOM element that jQuery will consider as the header element for each contact, and we will direct jQuery not to use the anchor element <a> that triggers the accordion effect for navigation. (In other words, the <a> will serve only to trigger the effect and the browser will make no attempt to follow the href="#" (which, in any case, is null.) The revised function looks like this:

$("#infolist").accordion({
    header: '.personName',
    navigation: false
});

Using CSS to Add Appearance Enhancements

Our project now has the behavior we want, but it looks quite plain and still lacks a well-organized appearance. We will address this by adding a set of CSS style definitions that will affect how some of the elements and classes of elements in the DOM will display.

  1. In NetBeans, right-click (on Mac, ctrl-click) on the Source Files node of our project.

  2. Select New >.

  3. Select Cascading Style Sheet….

  4. Name the file styles and click Finish.

  5. A new file named styles.css appears in the project and is opened in the editor.

  6. Replace the entire contents of the styles.css file with the following CSS code:

    body { width: 40em; margin: auto; }
    a { outline: none; }
    
    .ui-accordion {
    	 margin: 0; padding: 0;
    	 }
    .ui-accordion li {
    	 list-style-type: none;
    	 border-bottom: 2px solid white;
    	 }
    .ui-accordion li .ui-accordion-header {
    	 margin: 0; padding: 0 1em;
    	 font: bold 14px/28px sans-serif;
    	 color: #eef;
    	 background-color: #aaf;
    	 text-decoration: none;
    	 display: block;
    	 }
    
    a.personName:hover { color: white; }
    ul.infolist { display: block; }
    
    .person {
    	 background-color: #eef;
    	 margin: 0; padding: 0;
    	 border-bottom: 1px solid #ccf;
    	 }
    .person ul { padding: 0 3em 2em; }
    .person ul li {
    	 padding-top: 1em;
    	 border: 0 none;
    	 }
    
    li:before {
    	 color: #66f;
    	 font-weight: bold;
    	 display: inline-block;
    	 width: 4.5em;
    	 }
    
    li.portrait img {
    	 float: right;
    	 margin: 1em;
    	 border: 1px solid #ccf;
    	 }
    li.title:before { content: "Title: "; }
    li.office:before { content: "Office: "; }
    li.phone:before { content: "Phone: "; }
    li.email:before { content: "E-mail: "; }
    li.bio:before { content: "Bio: "; }
    

The CSS in styles.css accomplishes a variety of formatting tasks by specifying:

  • the spacing and relative placement of elements,
  • the width and height of certain elements,
  • the color of various elements, and
  • a generic sans-serif font for the contact persons' names.

Perhaps most interestingly, however, our CSS stylesheet, in the last few lines, specifies the content of text labels that identify the various semantic parts of the document. By putting such items in a stylesheet, we can easily make changes to all instances of the text labels, should the need arise, with a single edit to this one file.

It remains to connect our new stylesheet to our web application. We will use the @import CSS directive to import the stylesheet and apply it to elements of the DOM.

  1. Open index.html in the NetBeans editor. Find the style tag.

  2. Between the open and close style tags, enter the following:

    @import url("styles.css");
  3. Save.

Switch to the web browser and refresh to see the new CSS styles applied to the document. You should see something similar to this:

View in Browser

Selecting any of the names in the list (below the currently displayed contact) will show the accordion effect in action, together with the CSS styles that we have defined. As a small exercise, note the positions, spacing, and colors of various elements on the page and examine the CSS stylesheet to see if you can determine which rule(s) account for them.

Further Enhancements

Modifying the Animation Effect

We could end this tutorial right here, and you would have a basic understanding of how jQuery works. But jQuery also offers a simple mechanism for making all kinds of adjustments and customizations of seemingly limitless variety. To demonstrate this, we will alter the sliding animation that is triggered when we click on a contact link other than the one currently being displayed. We will add a jQuery effects library to accomplish this.

  1. Find the file "jquery.easing.js" in the .zip archive you downloaded earlier.

  2. Put this file into the js/ directory of the project folder.

  3. Add the following script tag immediately after the ui.accordion.js script tag, before the script tag with the (document).ready function.

    <script type="text/javascript" src="js/jquery.easing.js"></script>
  4. Change the object literal inside the accordion() function so that it reads:

    $("#infolist").accordion({
        header: '.personName',
        animated: 'easeslide',
        navigation: false
    });
    

    Note: The parameters in the object literal can go in any order, separated by commas. It is important to remember, however, that the final element in the array cannot be followed by a comma.

  5. Save, switch to your browser and refresh. When you select one of the contacts other than the one being displayed, you will see that the motion of the transition starts fast, gradually gets slower, and then speeds up at the end.

  6. Back in NetBeans, change the word easeslide to bounceslide.

  7. Save, then refresh the page again in your browser. When you test it, you will see that the transition is smooth in the upward direction, but in the downward direction, a bouncing effect is seen.

Modifying Page Contents

We can also use jQuery to modify the contents of a web page. You have probably noticed that the e-mail addresses that were used in the sample data set (the contact list) are obfuscated using the convention of replacing the @ with the literal English word "at" in parentheses, like this: (at). This is done to prevent spam harvesters from easily gleaning valid e-mail addresses from public-facing pages on the worldwide web. It's clever but it has at least a couple of drawbacks. One is that spam harvesters have become more sophisticated, and so some of them know about this (at) convention. Another is that it does not allow a person to simply click an e-mail link and quickly begin typing a message to that person, hampering usability and expected behavior.

We can address both of these using a jQuery plugin called "defuscator.js", which you will find in the .zip archive you downloaded earlier.

  1. Put "defuscator.js" into the js/ directory.

  2. Add a script link referring to it to the page, just as we've done above.

  3. Add the following line of code to the (document).ready function, at the end, but before the final set of brace-parenthesis-semicolon });.

    $(".email").defuscate();

    This command simply connects to all elements of the DOM where class="email" and runs the defuscate.js plugin on them.

  4. Save and refresh the browser. Observe that everywhere "(at)" has been replaced by "@", and that now the e-mail links are clickable and work as expected.

An interesting point about defuscator.js is that any text can be put between the parentheses () in place of "at". The function will work just the same. This may help to make it more robust against the better-equipped spam harvesters.

Summary

In this tutorial, you have learned how to install jQuery in your project and how to write some basic instructions using the jQuery syntax. You have learned how jQuery interacts with the Document Object Model, using variables that resemble CSS selectors, to affect the appearance and behavior of elements on a web page. You have also learned how to add jQuery plugins to your project to introduce highly customizable enhancements to your web pages.

Further, you have learned that jQuery can be used to modify the contents of a web page and turn static page elements into more dynamic ones.

Doing More

As an easy exercise, figure out a way to make the phone number appear in red. There are at least two ways. One uses a pure CSS solution, another uses jQuery. Show how this can be done using both ways.

As a harder exercise, find a way to make the bio for each contact invisible until the user clicks an element (a link or a button, for example) to display it. Use a jQuery animation to disclose the bio text in an interesting way. You will have to explore the jQuery web site (see links below) for the documentation explaining how to do this. There is a wealth of jQuery plugins available that you can experiment with, each with its own documentation explaining its use and what parameters can be set. Feel free to include one or more jQuery plugins in your solution.

Further Reading