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.
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).