jQuery & jQuery UI Tutorial

A Quick Introduction to jQuery

What is jQuery?

jQuery is a Javascript library that makes working with web pages much easier. I think the jQuery home page explains it best: jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

Why Use jQuery?

  • Simplify your code
  • Light Weight (~24K minified & GZipped)
  • Cross-Browser Compatibility
  • jQuery UI (~50K minified & GZipped)
  • Plugins
  • Well Supported
  • Good Documentation

jQuery makes it much easier to do DOM (Document Object Model) manipulation. For example, here's some regular Javascript code to change the color of all links on a page:

var ulElement = document.getElementById('jqExample1');
var mylinks = ulElement.getElementsByTagName('a');
for(var i=0; i < mylinks.length; i++) {
	mylinks[i].setAttribute("style", "color:red;");
}

...and here's how we would accomplish the same task using jQuery:

$("#jqExample2").find("a").css("color", "red");

Clicking the buttons below you can see that both code examples do the same thing:

Getting Started

First you will need a copy of jQuery and jQueryUI which you can download from here. On the download page you are given an option of which components and what theme you want to include. Just select all the components for now. You can choose which ever theme you'd like. I'm using the UI Lightness theme for these examples. The jQuery UI download includes a copy of the jQuery library so you don't have to download that separately.

To use the jQueryUI library you will first need to include the paths to the jQuery CSS and Javascript files in the <head> section of your HTML page. Here are the lines you'll want to add:

	<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.2.custom.css" rel="Stylesheet" />	
	<script type="text/javascript" src="js/jquery-1.4.2.min.js"</script>
	<script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script>

Note: You will probably need to change the version numbers in the code above depending on what version of jQuery and jQueryUI you are using.

If you've chosen a different theme than the default "UI Lightness" you'll need to replace "ui-lightness" in the CSS link statement with the name of the theme you want to use. This can be one of the jQueryUI pre-built themes or a custom theme you've created. custom themes can be easily created using the jQueryUI ThemeRoller tool.

jQuery Alias

When using jQuery the first thing you'll notice is lots of lines of code that begin with something like this: $("xyz"). The $() is an alias for jQuery() so the following lines are equivalent:
jQuery('p').css('marginBottom', '1em');
$('p').css('marginBottom', '1em');

Running Your Code

In order to run your code you'll want to first make sure that all the elements of the page have loaded. Of course, jQuery provides a simple way to do that by using the $(document).ready event

$(document).ready( function() {
		/* 
		 * your Javascript code goes here... 
		 */							
	}
)

Just put the code you want run when the page loads inside the inner function and you're set.

Selectors, Actions & Parameters

Of course just finding elements isn't very useful. Once found you're going to want to do something with them. Each jQuery command is usually made up three parts: a selector, an action and parameters. For example, in the command:

$('div.mydiv').css('color', 'green');

...the selector is $(div.mydiv'), the action is .css and the parameters are ('color', 'green'). Not every command is going to have parameters but the will always be a selector and an action.

The "selector" is the part that determines what your code is going to act on. The selector can be any valid CSS selector. For example, to find all links on your page you would enter:

$('a');

To find all divs with the classname 'content' you would enter:

$('div.content');

You can also select elements by id:

						$('#pageheading');

jQuery also has a number of it's own custom selectors as well. You can find more information about them here.

There are many actions to choose from as well. Let's take a look at a couple for working with classes and CSS properties.

Classes and CSS Properties

One of the most common actions is to be able to add and remove an elements class attributes. jQuery has a number of built-in functions for manipulating classes including: addClass, removeClass and hasClass.

	$('div.mydiv').addClass('selected'); 	// Add the 'selected' class to this element
	$('div.mydiv').removeClass('selected');	// Remove the 'selected' class from this element
	$('div.mydiv').hasClass('selected');	// Does this element have the 'selected' class?

You'll also want to be able to set CSS properties on an element. The 'css' function allows you to do just that:

Set a style property

$('div.left').css('float', 'left');

Get a style property

$('div.left').css('float'); // <-- Returns 'left'

To find out more about the jQuery CSS functions check the documentation which can be found here.

Events

Many times you want to wait for a certain event to occur such as a mouse click or a keypress before you run your code. jQuery makes it easy to add events to elements on your page.

Click me
Double-click Me
Move your mouse over me

Here's the code to trigger the events:

$('#jqExample3-click').click(function(){
	alert("You clicked me!");
});

$('#jqExample3-dblclick').dblclick(function(){
	alert("You double-clicked me!");
});

$('#jqExample3-mouseover').mouseover(function(){
	alert("You moved your mouse over me!");
});

You can see that we are using the click, dblclick and mouseover events as the actions. Just add the event action to your selector and you're set.

A Practical Example

Let's put everything altogether now and see what we can do. You may have noticed the little arrows on the left side of the section headings on this page. If you click the arrow it will open or close that section of the page using a nice jQuery transition effect. Here's the HTML code used to do that:

<div class="section">
	<h2 class="sectionHeading">Section Title Goes Here</h2>
	<div class="content">
		<p>Content coming soon...</p>
	</div><!-- end content -->
</div><!-- end section -->

...and the CSS:

.sectionHeading {
	background: #ffffff url(../images/orange-arrow-down.png) no-repeat scroll center left;
	padding-left: 28px;
	cursor: pointer;
}

.sectionHeading.closed {
	background: #ffffff url(../images/orange-arrow-right.png) no-repeat scroll center left;
}

...and finally, here's the Javascript code that makes it happen:

// Setup toggles for sections
$('.section').find('.sectionHeading').click(function(){
	$(this).toggleClass('closed');
	$(this).next().toggle('blind',500);		
});

You'll notice that we've used a couple of new actions: toggleClass and toggle. The toggleClass action looks for the class in the parameter. If it finds the class it removes it. If the class is not found it adds it to the element. In the example above we're looking for the 'closed' class in order to determine the direction of the arrow next to the heading.

The toggle action works to either show or hide an element. In this case we're looking for whatever element is after the .sectionHeading and we'll either show or hide it using the 'blind' effect. The number 500 is the time in milliseconds the effect will take (500 milliseconds = 1/2 second).

What Is jQuery UI?

jQueryUI is a library that provides a rich set of UI elements and effects that can be used in conjunction with the jQuery library. These UI elements include:

  • Accordion Menus
  • Date Picker
  • Tabs
  • Dialogs
  • Autocomplete
  • Button
  • Datepicker
  • Dialog
  • Tabs

as well as interactions and effects such as:

  • Draggable
  • Sortable
  • Selectable
  • Toggle Class
  • Effect

You can find all the details about the jQueryUI library on thier website which can be found here.

jQuery UI Widgets

Widgets are a collection UI controls that are built-in to the jQueryUI library.

Date Picker

The Date Picker, when added to a text input field, will pop-up a calendar when the user clicks in the field to make the input of dates simpler and more consistent. When someone clicks on the field the calendar is brought up and allows them to select a date. Once they make their selection the date is automatically entered in the input field. It's very easy to setup on any text input field. Here's a simple example. Just click the field below to try it out:

Default Date Picker

Here's the HTML code we used to display an input field:

Code
<form id="form1" action="submit" method="post">
    <label>Select Date</label>
    <input type="text" name="date" value="" id="dateInput1">
</form>

and here's the Javascript code to add a basic date picker to the input field:

Code
$("#dateInput1").datepicker();

In this example we're using the id attribute to select which field to add the date widget to. If you have multiple date fields on a page you might want to use the class attribute instead of the id to select all the fields with one line of code. The following code snippet will find all the items on the page that have the class "dateInput" and set them up to use the Date Picker widget:

Code
$(".dateInput").datepicker();

The Date Picker widget has lots of options that can be used to taylor it's behavior to your needs. Here are some other display options you might find useful:

  • Display multiple months

    Add the 'numberOfMonths' to display multiple months at once. This example also adds the button bar at the bottom of the calendar with "Today" and "Done" buttons.

    Example - Date Picker with multiple month display
    Code
      $("#dateInput2").datepicker( {
    	numberOfMonths: 3,
    	showButtonPanel: true
        }
      );
    
  • Allows Dates in a Specific Range

    In this example we allow date selection only within a specified date range using the minDate and maxDate options. We chosen 10 days before or after the current date (-10D, 10D). Replace the 'D' with 'W' for weeks, 'M' for months or 'Y' for years. You can also specify dates in the format mm/dd/yy.

    Example - Date Picker allowing selection only in specified date range
    Code
    $("#dateInput3").datepicker( {
    	numberOfMonths:2,
    	minDate: -10D, maxDate: '+10D'
      }
    );
    
  • Select a date range

    Here's an example that allows you to choose a start date and end date. It also displays 3 months at once.

    Example
    Code
      var dates = $('#dateInput4, #dateInput5').datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function(selectedDate) {
          var option = this.id == "dateInput4" ? "minDate" : "maxDate";
          var instance = $(this).data("datepicker");
          var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
          dates.not(this).datepicker("option", option, date);
        }
      });
    

There's lots more options available for this widget including setting the date format and changing various display settings. See the complete jQueryUI documentation for the Date Picker widget at: http://jqueryui.com/demos/datepicker/

Tabs

Using tabs to display different content is common on many web sites. The jQuery UI Tab widget makes creating this UI element very easy. Here's an example of the default Tabs widget behavior:

Default Tabs widget

Contents of Tab #1

Contents of Tab #2

Contents of Tab #3

Contents of Tab #4

Setting up the HTML for the Tabs widget is pretty simple. The tabs themselves are defined in an un-ordered list (ul) with each list item containing a link to the ID of the content. The content is then placed in divs below the list, each with the appropriate ID. Here's the HTML code from our example above:

Code
<div id="tabs1">
  <ul>
    <li><a href="#tabs1-1">Tab #1</a></li>
    <li><a href="#tabs1-2">Tab #2</a></li>
    <li><a href="#tabs1-3">Tab #3</a></li>
    <li><a href="#tabs1-4">Tab #4</a></li>
  </ul>
  <div id="tabs1-1">
    <p>Contents of Tab #1</p>
  </div>
  <div id="tabs1-2">
    <p>Contents of Tab #2</p>
  </div>
  <div id="tabs1-3">
    <p>Contents of Tab #3</p>
  </div>
  <div id="tabs1-4">
    <p>Contents of Tab #4</p>
  </div>
</div>

And here's the Javascript code that sets up the Tab widget:

Code
  $("#tabs1").tabs();

Like all the jQuery UI widgets there are many options available for changing the behavior of the tabs. Here's an example that makes it so the tab contents will be shown with a mouse-over instead of having to click:

  • Switch Tabs using mouse-over event instead of click

    Here's an example of how you can change which event triggers the tab change, in this case we're using the mouse-over event.

    Contents of Tab #1

    Contents of Tab #2

    Contents of Tab #3

    Contents of Tab #4

    Code
      $("#tabs1").tabs(event:"mouseover");
    
  • Draggable Tabs

    This example shows how you can use the jQuery UI "draggable" interaction to add the ability to drag the tabs and change their order:

    Example: Draggable Tabs

    Contents of Tab #1

    Contents of Tab #2

    Contents of Tab #3

    Contents of Tab #4

    Code
      $("#tabs3").tabs().find(".ui-tabs-nav").sortable({axis:'x'});
    

More information about the Tabs widget and it's options can be found at http://jqueryui.com/demos/tabs

Accordion Menu

The Accordion menu allows you to create a horizontal menu with collapsible sections

Default Accordion Menu widget

Here's the HTML used int he above example:

Code
<div id="accordion1">
  <h4><a href="">Section #1</a></h4>
  <ul>
    <li><a href="">Item #1</a></li>
    <li><a href="">Item #2</a></li>
    <li><a href="">Item #3</a></li>
  </ul>
  <h4><a href="">Section #2</a></h4>
  <ul>
    <li><a href="">Item #1</a></li>
    <li><a href="">Item #2</a></li>
    <li><a href="">Item #3</a></li>
  </ul>
  <h4><a href="">Section #3</a></h4>
  <ul>
    <li><a href="">Item #1</a></li>
    <li><a href="">Item #2</a></li>
    <li><a href="">Item #3</a></li>
  </ul>
</div>

And here's the Javascript code that creates the accordion menu:

Code
  $('#accordion1').accordion();
  • Collapse All Sections

    The default behavior of the Accordion menu is to always keep one section open. You can easily change that to allow all sections to be collapsible by adding the "collapsible" option. Here's an example:

    Collapse all sections

    Try clicking on one of the open section headings and you'll see the new collapsable behavior. Here's what the Javascript code with the option added looks like:

    Code
    $('#accordion2').accordion({ collapsible: true });
    
  • Open on Mouse Over

    Another option is to have the sections open just by moving the mouse over it instead of having to click the title. Try hovering your mouse pointer over the titles in the example below:

    Example: Open on mouse over

    Here's the Javascript code with the move-over option added:

    Code
    $('#accordion3').accordion({ event: "mouseover" });
    

Of course there are lots more options for this widget.See the complete jQueryUI documentation for the Accorion Menu widget at: http://jqueryui.com/demos/accordion

Dialogs

Standard Dialog
HTML Code
<div id="dialog1" title="Basic dialog">
  <p>This is the default jQuery UI non-modal dialog. Notice that you can still interact with other items on the page.</p>
</div>

<button id="dialogButton1" type="button">Show Standard Dialog</button>
Javascript Code
// Define the dialog box
$("#dialog1").dialog();

// Setup a button to open the dialog box
$('#dialogButton1').click(function() {
  $('#dialog1').dialog('open');
})
Modal Dialog
HTML Code
<div id="dialog2" title="Basic modal dialog">
  <p>This is an example of a modal dialog box. There is now a overlay over the screen blocking other items on the page.</p>
</div>
	
<button id="dialogButton3" type="button">Show Modal Message Dialog</button>
Javascript Code
$("#dialog2").dialog({ modal: true });

$('#dialogButton2').click(function() {
  $('#dialog2').dialog('open');
})
Modal Message Dialog
HTML Code
<div id="dialog3" title="Download complete">
	<p>
		<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
		This is an example of a message dialog. It's very similar to the modal dialog with the addition of the OK button at the bottom.
		<p>It also uses a ui-icon (the little checkbox image above) which we'll talk about later in this article.</p>
	</p>
</div>	
Javascript Code
$("#dialog3").dialog({
	modal: true,
	width: 400,
	buttons: {
		Ok: function() {
			$(this).dialog('close');
		}
	}
});	
Modal Confirmation Dialog
HTML Code
<div id="dialog4" title="Empty the recycle bin?">
	<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
Javascript Code
$("#dialog4").dialog({
	resizable: false,
	modal: true,
	height: 200,
	width: 400,
	overlay: {
		backgroundColor: '#000000',
		opacity: 0.5
	},
	buttons: {
		'Delete all items in recycle bin': function() {
			$(this).dialog('close');
		},
		Cancel: function() {
			$(this).dialog('close');
		}
	}
});	

$('#dialogButton4').click(function() {
	$('#dialog4').dialog('open');
})
Modal Form Dialog
HTML Code
<div id="dialog5" title="Create new user">
	<p id="validateTips">All form fields are required.</p>

	<form>
	<fieldset>
		<label for="name">Name</label>
		<input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" />
		<label for="email">Email</label>
		<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
		<label for="password">Password</label>
		<input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />
	</fieldset>
	</form>
</div>
Javascript Code
$("#dialog5").dialog({
	height: 380,
	width: 400,
	modal: true,
	buttons: {
		'Create an account': function() {
			$(this).dialog('close');
		},
		Cancel: function() {
			$(this).dialog('close');
		}
	},
	close: function() {
	}
});

$('#dialogButton5').click(function() {
	$('#dialog5').dialog('open');
})

This is the default jQuery UI non-modal dialog. Notice that you can still interact with other items on the page.

This is an example of a modal dialog box. There is now a overlay over the screen blocking other items on the page.

This is an example of a message dialog. It's very similar to the modal dialog with the addition of the OK button at the bottom.

It also uses a ui-icon (the little checkbox image above) which we'll talk about later in this article.

These items will be permanently deleted and cannot be recovered. Are you sure?

All form fields are required.

Effects and Transitions

Coming soon...

Notes and Alerts

Coming soon...

UI-Icons

Coming soon...

jQuery UI Themes

Coming soon...

Third-Party Plugins

FancyBox

Example

Click on an image to zoom in

Epiphone Jack Casady Signature Bass Fender Telecaster Hohner Jack Bass Ovation Celebrity Deluxe Sango Model 2845
Code - Scripts & CSS to include for FancyBox
<link rel="stylesheet" href="scripts/fancybox/jquery.fancybox-1.3.1.css" type="text/css" media="screen" />

<script src="scripts/fancybox/jquery.fancybox-1.3.1.pack.js" type="text/javascript"></script>
<script src="scripts/fancybox/jquery.easing-1.3.pack.js" type="text/javascript"></script>
<script src="scripts/fancybox/jquery.mousewheel-3.0.2.pack.js" type="text/javascript"></script>
Code - HTML for FancyBox
<div class="content">
	<a class="zoom" rel="group1" href="images/guitars/IMG_1161.jpg"><img src="images/guitars/IMG_1161-thumb.jpg" alt="Epiphone Jack Casady Signature Bass" /></a>
	<a class="zoom" rel="group1" href="images/guitars/IMG_1162.jpg"><img src="images/guitars/IMG_1162-thumb.jpg" alt="Fender Telecaster" /></a>
	<a class="zoom" rel="group1" href="images/guitars/IMG_1163.jpg"><img src="images/guitars/IMG_1163-thumb.jpg" alt="Hohner Jack Bass" /></a>
	<a class="zoom" rel="group1" href="images/guitars/IMG_1164.jpg"><img src="images/guitars/IMG_1164-thumb.jpg" alt="Ovation Celebrity Deluxe" /></a>
	<a class="zoom" rel="group1" href="images/guitars/IMG_1165.jpg"><img src="images/guitars/IMG_1165-thumb.jpg" alt="Sango Model 2845" /></a>
</div>						
Code - Javascript for FancyBox
$("a.zoom").fancybox({
	'transitionIn'	:	'elastic',
	'transitionOut'	:	'elastic',
	'showCloseButton': true,
	'overlayOpacity': 0.6,
	'overlayColor': "#000000",
	'speedIn'		:	600, 
	'speedOut'		:	200,
	'titlePosition'	: 'inside'  
});