Introduction to jQuery

JavaScript has been around for many years and is used widely for enhancing the user experience in Web applications. However, to write JavaScript enhancements from scratch, for example, to provide hiding/showing of content, is time-consuming and, with the arrival of JavaScript libraries such as jQuery, pointless.

JavaScript coding has required much patience to make even straightforward UI enhancements reliable across the many browser versions and types. jQuery provides a core library (plus additional libraries) which take away the uncertainty in JavaScript coding.

If you want to see some raw JavaScript, look at the source for this websites home page, which provides a simple accordion hide and show of content for each tutorial. The code runs to 27 lines, plus a click handler for each tutorial link. With jQuery there is no need for separate click handlers and it only requires 12 lines of code and with a better UI experience - we'll see how this is achieved in this introductory tutorial.

Getting started

To use jQuery you need to have a reference to the jQuery script library (currently at version 1.7.1). You can link to an externally hosted version, or download it to a folder in your own site. This tutorial takes the latter approach and the script reference is in the <head> section as follows:

  <script src="/scripts/jquery/jquery-1.7.1.min.js"
         type="text/javascript"></script>

To use the jQuery library we add our own script section, but we must make sure wee don't attempt to call the library before the web page is ready. We do this by wrapping our code in a function which will be called when the document has loaded. The start code for this is:

 <script type="text/javascript">
  $(document).ready(function() {
    // do stuff when the page is ready
  });
</script>

This code needs some explanation. In jQuery, the '$' symbol is a reference to jQuery itself. Inside the brackets we select what we want to work with. In this case we want the document object, though you can use all combinations of selectors to identify what you want to work with. For example, $(".rightImage") will select all elements in your web page with the class rightImage. After the selection we can call a range of jQuery built in functions to act on the element(s) we've selected. In our case we want to enable the 'ready' event which only happens once the document is fully loaded. Here we set the ready function to an actual JavaScript function with 'stuff' inside it.

This paragraph has class 'readydemo' and started life as a simple plain paragraph just like the previous paragraph. However, you can see it changed font using the following jQuery code:

  $(document).ready(function() {
   $(".readydemo").css
          ({fontFamily:"'Times New Roman', times, serif",
            color: "Maroon"});
 });

Complete documentation for jQuery and its functions is available on the jQuery documentation site.

Making a simple accordion

We are going to start with a simple list of html headings and paragraphs which we want to animate. Clicking a heading will make its paragraph show or hide. For this we need to give our headings class names so we can select them using jQuery. We will attach a click handler to each of the headings, so that we can toggle the paragraphs on an off. All this can be accomplished in the documents 'ready' handler.

The xhtml for the document is:

 <h5 class="toggleHeader">Heading A</h5>
<p>Paragraph for heading A ...</p>
 <h5 class="toggleHeader">Heading B</h5>
<p>Paragraph for heading B ...</p>
 <h5 class="toggleHeader">Heading C</h5>
<p>Paragraph for heading C ...</p>
 <h5 class="toggleHeader">Heading D</h5>
<p>Paragraph for heading D ...</p>

The initial piece of jQuery will hide the paragraphs:

 <script type="text/javascript">
  $(document).ready(function() {
    $(".toggleHeader").next().hide();
    // rest to come!
  });
</script>

The selector get all elements with class '.toggleHeader'. The next() function gets the element after it (i.e. the <p> element) and the hide() function hides the <p> element.

Now we need a click handler for the headings:

 <script type="text/javascript">
  $(document).ready(function() {
    $(".toggleHeader").next().hide();
    $(".toggleHeader").click(function () {
      $(this).next().slideToggle(600);
    });
  });
</script>

Notice the selector $(this) in the function. This is the identity of the object that generate the event/function call.

Check out the following headings which use the above code.

Humpty Dumpty

Humpty Dumpty sat on a wall,
Humpty Dumpty had a great fall.
All the king's horses and all the king's men
Couldn't put Humpty together again

Little Miss Muffet

Little Miss Muffet Sat on a tuffet,
Eating her curds and whey;
Along came a spider,
Who sat down beside her
And frightened Miss Muffet away

Twinkle Twinkle Little Star

Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.

Little Bo Peep

Little Bo-Peep has lost her sheep,
And doesn't know where to find them;
Leave them alone, And they'll come home,
Wagging their tails behind them

Using jQuery plugins

The jQuery library itself provides a large set of functions which allow you to animate, generate, manipulate content. Refer to the documentation site linked above. However, there is a body of developers who, having built a useful jQuery feature, will publish their work as a jQuery plugin. If you find a plugin it is usually just a matter of downloading it to your script folder, put a <script> element to load it, and then calling it when required. Most plugins provide parameters which can be set when you initialise them. Quite often they have CSS files to provide styling for the effects they provide. In some cases you don't even need to call the function, as long as you provide default markup structure that the plugin understands

Example plugin - Lightbox

Lightbox is a plugin for enhancing thumbnail image browsing. The download is available on the authors Lightbox site. The lightbox plugin is a good example of a plugin which works with minimal extra coding. It requires a simple <script> link to the plugin and a CSS link for the styling. The HTML code is quite straightforward and simply needs a class name on the anchor to identify the thumbnail link. If you want to group pictures so they can be browsed just add a 'rel' attribute to each anchor (e.g. "rel=ferrari")e.g.

 <a href="images/Ferrari1.jpg" class="lightbox" rel="ferrari"
   title="Ferrari picture 1">
  <img src= "images/Ferrari1thumb.jpg" alt="Ferrari picture 1"/></a>
<a href="images/Ferrari2.jpg" class="lightbox" rel="ferrari"
   title="Ferrari picture 2">
  <img src= "images/Ferrari2thumb.jpg" alt="Ferrari picture 2"/></a>
<a href="images/Ferrari3.jpg" class="lightbox" rel="ferrari"
   title="Ferrari picture 3">
  <img src= "images/Ferrari3thumb.jpg" alt="Ferrari picture 3"/></a>
<a href="images/Ferrari4.jpg" class="lightbox" rel="ferrari"
   title="Ferrari picture 4">
  <img src= "images/Ferrari4thumb.jpg" alt="Ferrari picture 4"/></a>

The jQuery code is simply:

<script src="jquery.lightbox.js" type="text/javascript"></script>
 <script type="text/javascript">
   $(document).ready(function(){
     $(".lightbox").lightbox();
</script>
Lightbox demo

Ferrari picture 1 Ferrari picture 2 Ferrari picture 3 Ferrari picture 4

Example plugin 2 - Cycle

Cycle is a plugin that allows you to create a slideshow and it supports many transition effects. In its simplest form you place all your images in a <div> and call the Cycle plugin with the selected <div> and a single option with the type of transition. The plugin support much more than this and full details are given on the cycle plugin website. A simple slideshow of the ferrari pictures requires HTML as follows:

<div id="ferraris">
  <img src="images/ferrari1.jpg" width="200"
       alt="Ferrari picture 1" />
  <img src="images/ferrari2.jpg" width="200"
       alt="Ferrari picture 2" />
  <img src="images/ferrari3.jpg" width="200"
       alt="Ferrari picture 3" />
  <img src="images/ferrari4.jpg" width="200"
       alt="Ferrari picture 4" />
</div>

and the required jQuery startup code is:

<script type="text/javascript">
 $(document).ready(function() {
   $('.slideshow').cycle({ fx: 'fade'
   //or scrollUp, shuffle, etc...
   });
 });
</script> 
Cycle demo
Ferrari picture 1 Ferrari picture 2 Ferrari picture 3 Ferrari picture 4

Example plugin 3 - Tablesorter

Tablesorter is a jQuery plugin which allows you to add sorting of columns in a table without having to reload the page. On top of basic functionality it provides more advanced features which are detailed in the Tablesorter documentation. In its basic form you simply call the tablesorter function on your selected table. Your table must have its column headers in a <thead> element and the data rows must be in a <tbody> element. For example:

<table id="lettertable" class="tablesorter">
  <thead>
    <tr><th>Letter</th><th>Word</th></tr>
  </thead>
  <tbody>
    <tr><td>A</td><td>Hay</td></tr>
    <tr><td>B</td><td>Bee</td></tr>
    <tr><td>C</td><td>Sea</td></tr>
  </tbody>
</table>

and the jQuery to enable sorting is simply:

<script type="text/javascript">
  $(document).ready(function() {
    $("#lettertable").tablesorter();
  });
</script>
Tablesorter demo

This example makes use of a stylesheet (modified from one in the plugin site) to style the table.

LetterWord
AHay
BBee
CSea

And now the jQuery version of the homepage accordion!

The jQuery code is:

<script type="text/javascript">
  $(document).ready(function () {
    $(".tutsummary span").html("More info ...");
    $(".tutsummary span").css("cursor", "pointer");
    $(".tutsummary span").click(function () {
    if ($(this).html() == "More info ...")
      $(this).html("Hide info")
    else
      $(this).html("More info ...");
    $(this).next().slideToggle(600);
    });
    $(".tutsummary div").hide();
  });
</script> 
Scotty's tutorials
  • XHTML

    Introduction - XHTML is a standard for representing the structure and content of a web page. Its predecessor HTML not only represented the content and structure, but also included aspects such as the presentation of the information on the screen. However, attempting to change the design and presentation of the information using XHTML is now frowned upon and all page styling should now be done using a technique/standard called Cascading Style Sheets (CSS). This change of emphasis is a mixed blessing. It makes creation of page content very straightforward, and simplifies the XHTML data file, however, to make the page look 'cool' requires a lot of effort using CSS. This introduction to XHTML will only deal with the basic XHTML elements for coding the structure and content of a web page. CSS will be dealt with in a later tutorial. Reference to 'high end' web creation tools, such as Dreamweaver and Expression Web, is avoided. The emphasis is on understanding the mechanics of web page cre...

  • CSS

    Introduction to CSS - Cascading Style Sheets (CSS) define how to display XHTML. The XHTML tutorial stressed the importance of separating content from style. XHTML simply codes the structure and content of the web page. CSS provide a powerful technique for determining the presentation of a webpage on a display and/or device. Although CSS techniques can be used within a web page to perform styling at the level of the whole page and even down to the level of an individual element, we will avoid this use. The power of CSS is in their ability to control the presentation of all the pages in a website. Multiple style sheets are allowed and the combined effect will be applied to the page by cascading the effects of each in turn. The WWW Consortium standards for CSS versions 1, 2 and 2.1 provide a comprehensive, unambiguous, definition of CSS. However, it is recommended that you become familiar with basic CSS from this tutorial and the W3Schools CSS Tutorial before trying to dig into the s...

Valid XHTML 1.0! | Valid CSS! | WCAG Approved AA
Page design by: John P Scott - Hosting with: Netcetera