Technical Article

Part Two: Introduction to JQuery -- a Powerful JavaScript Library

by Julien Dubois
Published July 2010

JQuery, a popular open source JavaScript Library, provides many advanced and cross-browser functions that can enhance your web applications. This article starts with the basics and then shows you how to extend JQuery with its plug-in system.

Downloads:

Note: This article was written and tested using NetBeans IDE 6.8.

Introduction

This article is part 2 of a four-part series. The first article, Part 1: Introduction to Jersey—a Standard, Open Source REST Implementation, introduced basic Representational State Transfer (REST) principles, and then built a sample application.

Note: You do not need to have already completed the exercises in the first article to follow this article. Also, you can download the sample application for the first article using a link provided at the end of the first article.

This second article introduces JQuery, an extremely popular, open source JavaScript library. We will start by looking at the current state of the art in JavaScript technology to see why JQuery is used in many impressive applications.

We will then use our case study from the first article in order to create a simple HTML page, which will serve as the basis for a hands-on tutorial for performing the following tasks using JQuery functionality:

  • Selecting HTML elements with JQuery
  • Manipulating HTML elements
  • Adding some animations to the Web page
  • Using JQuery UI to add a custom theme
  • Extending JQuery with the numerous available plug-ins

At the end of this article, we will have a user-friendly HTML and JavaScript front end, ready to be used for our application.

Why Use JQuery Instead of Just Basic JavaScript?

JavaScript is a fairly low-level programming language. It does not provide advanced page manipulation and decoration functions, and it provides nothing concerning animations. Moreover, using direct JavaScript can cause issues related to browser incompatibilities. Those issues have made many JavaScript applications difficult to code, resulting in high maintenance costs.

JQuery aims to ease all these problems by providing a lightweight library that adds many advanced and cross-browser functions to the standard language. In addition, there is a very dynamic community that adds more-advanced components based on JQuery.

A modern Web application wouldn't be complete without some AJAX functionality. JQuery provides functions for sending HTTP GET and POST requests, and it can work easily with the JavaScript Object Notation (JSON) format we saw in the first article. This functionality enables us to query the REST back end we coded in the first article.

Installing JQuery

JQuery is a JavaScript library, so installing it is just a matter of importing a script inside a Web page. However, there are a few best practices to be aware of:

  • JQuery is available through several content delivery networks (CDN). Using those CDNs instead of installing JQuery on your servers should provide significant performance and bandwidth gains.
  • As with any static content, JQuery files should be served compressed. That's why there are two versions of JQuery available: a minified (or “min”) version, which is small and efficient, and a development version, which is easier to read and debug. For the rest of this article, we will use the min version, which is enough for our needs.
  • JQuery files should be cached on the client side, so you should use the JQuery version number in the file name.

Let's start with a simple HTML Web page, which will be used for our sample application.

  1. Launch NetBeans and re-open the ArticleEvaluator project from the first article.
  2. Right-click the Web Pages node and select New > Web > HTML.
  3. Name your page article and click Finish.
  4. Replace the content of the newly created file with this HTML code:

   
<html> 
<head>  
  <title>Sample article</title>  
  <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>  
  <style type="text/css" media="screen">   
   @import "style.css";  
  </style> 
</head> 
<body>  
  <h1>Sample article</h1>  
  <p>Article text</p>  
  <div id="author-wrapper">    
    <div id="author">1</div>  
  </div> 
</body> 
</html>


As you can see, this file refers to a CSS file that you need to create:

Right-click the Web Pages node and select New > Web > Cascading Style Sheet.

Name your page style and click Finish.

Here is the content to copy and paste for this file:



body {     
    background: #ebe9e9;     
    margin: 0px;     
    padding: 0px;     
    font: 12px arial, sans-serif; 
}  

p {     
    background: #ffffff;     
    margin: auto;     
    border:2px solid #666666;     
    text-align: left;     
    font: 12px arial, sans-serif;     
    width: 500px; 
}  

h1 {     
    margin-top: 10px;     
    font: 20px arial, sans-serif;     
    color: #ff3333;     
    font-weight: bold;     
    text-align: center; 

} 

#author-wrapper {
    margin: auto;
    text-align: right;
    width: 500px;
    display: none;
}

#vote-form {
    margin: auto;
    width: 500px;
}


To test your HTML page, you can launch GlassFish (as in the first article) and point your browser to http://localhost:8080/ArticleEvaluator/article.html. You can also open this Web page directly from the file system, because it is just a static HTML file.

Selecting Elements with JQuery

The easiest way to get started with JQuery is to select some elements on our sample Web page.

Let's select the author division, which we copied and pasted in the previous section, in order to change this element to display some user information. As you can see from the HTML code and the CSS file, it currently contains the user ID, and it is included in a hidden <div> element. There are several ways to select this HTML element. Let's start by using its ID:

$("#author");

$ is not a JavaScript-specific keyword. It's a one-letter function that is defined by JQuery. The text that is passed to this function is parsed by JQuery, which then generates the correct series of JavaScript functions to select the requested Document Object Model (DOM) elements. This method of selecting DOM elements is concise and browser-independent, which addresses the two most important problems that arise with JavaScript programming. As a result, JQuery enables quick, simple, and powerful cross-browser selection of DOM nodes in the Web page.

Of course, the ID is not the only way to select elements. You can use the elements' class or some properties of those elements. For example, you can select all the elements with the vote class:

$(".vote");

In order to read the author's ID from our Web page, add the following code just before the closing </body> tag:



      <script type="text/javascript">
          $(document).ready(function() {
            var id = $("#author").text();
          });
      </script>



This task illustrates a common best practice with JQuery: The $(document).ready() function is launched when the Web page is ready, and it is loaded at the end of the page. From a user point of view, this means the whole page loads normally, and then JQuery is used to enhance the page.

Using the previous code, the author's ID will be read at startup time. You can test this by using the JavaScript alert() function.

Manipulating a Web Page's Elements

After HTML elements have been selected, you will certainly need to manipulate them by changing their CSS class, adding some text, or even replacing them completely. JQuery provides functions for all those tasks.

The use case we are going to implement is to replace the author's ID, which we selected earlier, with this author information: author's first name, author's last name, and a URL. For the moment, this information will be stored statically inside our JavaScript code, but in the third article of this series, we will get this information from the REST back end we coded in the first article.

Here is the author's information we are temporarily hard-coding in the JavaScript code:



function Author(id, firstName, lastName, url) {  
  this.id = id;  
  this.firstName = firstName;  
  this.lastName = lastName;  this.url = url; 
  }  

var author = new Author("1", "Julien", "Dubois", "http://www.oracle.com");




Because we already read the author's ID and we already know how to select the author's <div> element, we can replace the text from this element:



$("#author").replaceWith("Author: <b>" + author.firstName + " " + author.lastName +                 
     "</b><br/>" + "website: <a href=\"" + author.url + 
            "\">  + author.url + "</a>");




JQuery provides numerous other functions to change an HTML element. For example, we can make an element appear or disappear using the show() and hide() functions. An alternative way would be to change the CSS class used by an element; for this, JQuery provides functions to add a class, remove a class, or test whether a class is present.

Now that the author's ID has been replaced by the author information, let's display this information, which is the topic of the next section.

Adding Animations

Displaying an element is nice, but it is a lot more user friendly (and fun!) to add some animations. JQuery provides a rich set of animations that enables a very smooth user experience.

You can test all the animations on JQuery's Web site: http://jquery.com/

Of course, if you abuse these animations, your Web site will become difficult to use. So you need to find the right balance to have a nice-looking Web site.

For displaying the author information, we do not want something too flashy, because the author information is not the most important part of the page. Let's select a simple slide-down animation:

$("#author-wrapper").slideDown("slow");

Using animations with AJAX is very important from a user perspective:

  • Animations hide the fact that some requests take time to be processed server-side.
  • Animations attract the user's attention to what is changing on the Web page. Without an animation, a user might not notice that part of the page changed.

Using a JQuery Theme

JQuery UI is an extension to JQuery that adds widgets and themes on top of JQuery. JQuery UI is hosted at http://jqueryui.com/.

JQuery UI provides higher-level components, such as calendars, dialog boxes, auto-completed fields, and tabs, that all have the same look and feel. The result is similar to what we can do with JavaServer Faces technology, except the components here are fully rendered using JavaScript. Most of the components can work with AJAX. For example, the Autocomplete widget can get its data from local JavaScript code or from a call to a remote URL.

Several themes are provided as examples, but the most impressive part is an online application, http://jqueryui.com/themeroller/, that allows you to dynamically create your own custom theme. This theme can then be downloaded and used inside an application simply by importing the custom JavaScript, CSS, and images that are generated.

Here is an example configuration, in which the JQuery UI theme was unzipped in the jquery folder:



<head> 
  <title>Sample article</title>  
  <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script> 
  <script src="jquery/js/jquery-ui-1.8.2.custom.min.js"></script>  
  <style type="text/css" media="screen">    
    @import "style.css";   
    @import "jquery/css/custom-theme/jquery-ui-1.8.2.custom.css"; 
  </style>
</head>




We are not using JQuery UI and its widgets system in our sample application. So you should not add this code to your ArticleEvaluator code, because it will not have any effect.

If we were using JQuery UI, the generated theme would have automatically decorated all JQuery UI widgets. Of course, you can still use the theme to explicitly decorate your own elements by directly giving them a specific JQuery UI class.

Extending JQuery with Its Plug-in System

One of the reasons for the success of JQuery is its vibrant community, which provides hundreds of high-quality plug-ins. Our application still needs some very important functionality: the ability to vote for the articles. Hence, we would like to use a rating plug-in that provides us with a graphical view of the vote. At the JQuery Web site, it is easy to find some plug-ins related to our need by using this specialized search engine: http://plugins.jquery.com/

However, for the following reasons, use care when selecting a plug-in: The plug-ins are not supported by JQuery. The plug-ins' authors usually indicate which JQuery version their plug-ins are compatible with, but there can be issues if you use many plug-ins and you want to upgrade JQuery. The licenses can differ; your company probably will want to avoid any GPL-licensed plug-in. There is often more than one plug-in available for a particular need. It is then a matter of selecting the most appropriate one.

For our sample application, let's select the JQuery Star Rating plug-in:

http://github.com/fyneworks/star-rating

To use this plug-in, you need to import its JavaScript script and CSS file in the sample Web page:

  1. Download the plug-in, using the link above. For this article, we've used version v3.13 of the plug-in.
  2. Unzip the downloaded file to a folder called star-rating inside the web folder of your application. (This web folder is displayed as Web Pages inside NetBeans.)
  3. Add the plug-in's JavaScript and CSS files inside the header section of your Web page:


<head>  
  <title>Sample article</title>  
  <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>  
  <script src="star-rating/jquery.rating.js"></script>  
  <style type="text/css" media="screen">    
    @import "style.css";    
    @import "star-rating/jquery.rating.css";  
   </style> 
</head>




This plug-in works by enhancing existing radio buttons on the Web page. For this functionality, we need to create an HTML form containing those buttons. Copy and paste the following code just before the author-wrapper division element:



<form id="vote-form">Rating      
<input name="star1" type="radio" class="rating" value="1"/> 
<input name="star1" type="radio" class="rating" value="2"/> 
<input name="star1" type="radio" class="rating" value="3"/> 
<input name="star1" type="radio" class="rating" value="4"/>
<input name="star1" type="radio" class="rating" value="5"/> 
</form>
<br/> 

Using the plug-in is then just a matter of selecting the radio buttons that have the rating class and invoking the rating() function provided by the plug-in:



$(".rating").rating({  
  callback: function(value, link){   
    alert("The value selected was '" + value + "'.");  
   } 
  });


In the previous example, we added a callback function so we know which radio button was clicked.

Of course, this doesn't trigger any process in our application back end; the votes are not saved anywhere. In the third article of this series, we will send this data to our application back end so we have the full system working.

Conclusion

In this article, we demonstrated how to select, manipulate, animate, and extend a simple Web page. We saw that JQuery is very easy to use and we did not worry at all about cross-browser issues, because JQuery provides an abstraction layer that protects us from those problems.

A completed sample application can be downloaded here:

JQuery Sample Application (zip)

This sample application contains the code from the REST application we coded in the first article plus the article.html page we coded in this article, which is located in the web folder.

In the next article, we will link this Web page to the REST back end in order to have a complete application.

See Also

About the Author

Julien Dubois has been a Java developer and architect for more than 10 years. He is the co-author of a top-selling French book on the Spring Framework, and even worked for SpringSource before the company got bought by VMWare. He now leads his own consulting company, Responcia, which provides a French knowledge management solution.