After a decade-long frustrated effort in which I've tried all manner of libraries, frameworks, and other solutions in the hopes of lessening my utter contempt for JavaScript, I'm somewhat stunned to report the search is finally over. I doubt Ponce de Leon would be sporting a bigger grin had he found the fountain of youth. The solution is jQuery, and in mere weeks it has radically changed my mindset when working with JavaScript, resulting in the production of more powerful code and with it, more interesting website features.
In this tutorial I'll introduce you to jQuery by way of 17 examples. By installing jQuery and following along with these examples you'll be quickly and painlessly acquainted with the library's fundamental features. At the conclusion of this tutorial you'll find a zip file containing all of the code for each example. In addition to ordering the examples in a logical progression of increasing complexity, I've also divided them into the following categories. If you're completely new to jQuery, consider reading the tutorial in its' entirety; otherwise use the links to skip to a desired section.
Before moving on to the examples, I'll first show you how to add jQuery to your website.
jQuery is self-contained within a single JavaScript file. To download it, head on over to the jQuery website and navigate to the current release. There you'll find a "minified" and an uncompressed version of the latest release. You should use the former version in a production environment as all code formatting has been eliminated, thereby resulting in a smaller file size resulting in improved loading performance. Use the latter version if you'd like to peruse the source code.
Choose the desired version and save the file to an appropriate location within your website. Then reference the file within the confines of your website's
tags like so (you may need to adjust the path depending upon where you saved the jQuery file):<script type="text/javascript" src="/javascript/jquery-1.3.2.min.js"></script>
Because much of your time spent working with a JavaScript library such as jQuery will involve manipulating the HTML DOM (the DOM comprises all of the various page elements which you may want to hide, toggle, modify, or animate), you'll want to make sure the jQuery JavaScript doesn't execute until the entire page has loaded to the browser window. Therefore you'll want to encapsulate your jQuery code within the ready() event, like this:
<script type="text/javascript">
$(document).ready(function() {
alert("Welcome to my jQuery tutorial.");
});
</script>
Add this code within the
tags, making sure it appears below the reference to the jQuery file, and call the page from your browser. You'll see the alert window presented in Figure 1.
Figure 1. Triggering an Alert Window with jQuery
To retrieve text found in a particular DIV, use the text() method like so:
<script type="text/javascript">
$(document).ready(function() {
alert($("#favorite").text();
});
</script>
...
<body>
<p id="favorite">The Sun Also Rises, by Ernest Hemingway</p>
Executing this example produces the alert window shown in Figure 2.

Figure 2. Retrieving DIV text
The text() method will filter out any HTML tags found within the targeted element. So for instance if the book title were italicized like the following, using text() you would still see the same result as shown in Figure 2:
<p id="favorite"><i>The Sun Also Rises</i>, by Ernest Hemingway</p>
If you want to retrieve the text and tags, use the html() tag, as demonstrated next:
<script type="text/javascript">
$(document).ready(function() {
alert($("#favorite").html());
});
</script>
Executing this revised example produces the alert window shown in Figure 3.
Figure 3. Retrieving DIV text and HTML
To update the text found within a specific element, all you need to do is pass the text into the text() method, as demonstrated here:
<script type="text/javascript">
$(document).ready(function() {
$("#favorite").text("Fear and Loathing in Las Vegas.");
});
</script>
<div id="favorite">The Sun Also Rises</div>
The text() method will interpret anything passed into it literally, meaning any HTML found in the text will be encoded and output to the browser as text. If you want to pass in HTML, use the html() method:
<script type="text/javascript">
$(document).ready(function() {
$("#favorite").html("<i>Fear and Loathing in Las Vegas</i>");
});
</script>
It's common to modify an element's CSS class in response to some event, such as failure to complete all of a form's required fields. You can add a class to an element using the addClass() method, as demonstrated here:
<style type="text/css">
.highlight {
width: 250px;
background: orange;
color: white;
padding: 5px;
border: 2px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("#favorite").addClass("highlight");
});
</script>
</head>
<body>
<p id="favorite">The Sun Also Rises</p>
</body>
It's also possible to remove an element's class using the removeClass() method. Finally, you can toggle a class using the toggleClass() method.
Because jQuery or a server-side language such as PHP could dynamically create DOM elements based on some predefined criteria, you'll often need to first verify an element's existence before interacting with it. However, you can't just check for existence, because jQuery will always return TRUE even if the DIV does not exist:
if ($("#favorite")) {
alert("The favorite div exists!");
}
However, an easy way to verify existence is to use one of the properties exposed to each available DIV, for instance length:
if ( $("#favorite").length > 0 ) {
alert("The favorite div exists!");
}
Occasionally you'll want to remove an element from the page. To do so, you can use the .remove() method. For instance, the following example will remove the element identified by the news ID from the page:
<script type="text/javascript">
$(document).ready(function() {
favorite").remove();
});
</script>
</head>
<body>
<div id="favorite">The Sun Also Rises</div>
</body>
jQuery can also change the CSS class of multiple elements. For instance, suppose you wanted to stylize list items in the manner shown in Figure 4.

Figure 4. Stylizing Multiple Elements
You can do this in a manner almost identical to that demonstrated in Example #4, the only difference being you will add the highlight class to all li elements rather than to a specific DIV, as demonstrated here:
<style type="text/css">
.highlight {
width: 250px;
background: orange;
color: white;
padding: 5px;
border: 2px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("li").addClass("highlight");
});
</script>
</head>
<body>
<ul>
<li>The Sun Also Rises</li>
<li>Fear and Loathing in Las Vegas</li>
<li>I Am Legend</li>
</ul>
</body>
All of the examples presented so far presumed no involvement by the user, which for the most part would largely negate the need for JavaScript in the first place. In this section I'll show you how to incorporate interactive elements into your pages using jQuery's event handling capabilities.
jQuery can be configured to monitor the status of a particular DIV, class, or HTML tag, and respond to different types of user interactions with the element. jQuery actually supports numerous approaches to tying an event to an element, however the easiest involves using an anonymous function as demonstrated below. This example will cause an alert window to appear when the user clicks on the link identified by the external ID.
$(document).ready(function() {
$("#external").click( function (eventObject) {
alert("Warning! You are about to leave this sweet website!");
});
});
...
<p>
Click <a href="http://www.easyphpwebsites.com/" id="external">here</a> to go to EasyPHPWebsites.com.
</p>
Because jQuery is capable of accessing elements according to not only their DIV ID, but also their class type and element type, you can attach an event to all hyperlinks assigned the external CSS class:
$(document).ready(function() {
$(".external").click( function (eventObject) {
alert("Warning! You are about to leave this sweet website!");
});
});
...
<h3>My Favorite Links</h3>
<ul>
<li><a href="http://www.google.com/" class="external">Google</a></li>
<li><a href="/blog/">EasyPHPWebsites Blog</a></li>
<li><a href="http://www.twitter.com/" class="external">Twitter</a></li>
</ul>
The click() method is just one of several event handlers supported by jQuery. Among others, you can attach events to mouseovers, double clicking, form submissions, form field focus and changes, and much more. Consult the jQuery documentation for a complete list of handlers.
Tying a jQuery action to an event such as a hyperlink or submit button will not prevent the element's default behavior from also occurring. For instance, if you execute examples #8 and #9 the alert box will indeed appear as expected, however once the alert box is closed you'll be transported to the external page. You'll often want to prevent this default behavior from occurring. To do so, call event.preventDefault() within the function tasked with handling the event. I'll revise the example #X JavaScript to include this call:
$(document).ready(function() {
$(".external").click( function (eventObject) {
eventObject.preventDefault();
alert("You're not going anywhere!");
});
});
JavaScript has long played a significant role in helping out with form validation and manipulation. In this section I'll show you how to retrieve, manipulate, modify, and validate form-related data.
jQuery offers a convenient way to retrieve form field values, done by identifying the form field according to the field type and field name. For instance, you would retrieve the value of a text field named email like this:
$("input:email").val()
You can retrieve the value of a select box named country like this:
$("select:email").val()
Of course, if each form element is assigned an ID, there's nothing stopping you from retrieving the email field (presuming it's assigned a DIV ID of email) with the syntax we've been using throughout this tutorial:
$("#email").val()
The following example will display an alert box containing the user's input name when the form's submit button is pressed:
$(document).ready(function() {
$("#registration").submit( function (eventObject) {
alert("Hi, " + $("input:name").val());
eventObject.preventDefault();
});
});
...
<form id="registration">
<p>
<label for="name">Your Name</label><br />
<input type="text" name="name" value="" size="35" />
</p>
<input type="submit" name="submit" value="Register!" />
</form>
Like DIVs and other elements, you can set a form field's value by passing a parameter into the val() method. For instance, the following line will set the user's name to John Smith:
$("input:name").val("John Smith")
Suppose you're collecting geographical data regarding your website users at the time of registration. You'd like to collect the state-of-residence for American users, but hide that particular field for international users. To do this, we can watch the select box used to select the country, and if the user sets it to "United States", we'll display the state-specific select box:
<script type="text/javascript">
$(document).ready(function() {
$("#country").change( function (eventObject) {
if ($("#country").val() == "233") {
$('#state').show();
}
});
});
</script>
...
<form>
<p>
<label for="name">Your Name</label><br />
<input type="text" name="name" value="" size="35" />
</p>
<p>
<label for="country">Your Country</label><br />
<select id="country" name="country">
<option value="">Choose a Country:</option>
<option value="1">Afghanistan</option>
<option value="2">Aland Islands</option>
<option value="233">United States</option>
</select>
</p>
<p id="state" style='display:none;'>
<label for="state">Your State</label><br />
<select name="state">
<option value="">Choose a State:</option>
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
</select>
</p>
</form>
Incidentally, if you wanted to retrieve the select option's text instead of value, you'll first need to determine which option has been selected by passing along the :selected attribute, and then use the text() method to retrieve the text, like this:
$("#country :selected").text()
Radio buttons are intended to provide the user with a way to exclusively identify one of several options, for instance a favorite sport. You can identify which radio button in the group has been selected using the :checked filter in conjunction with identification of the radio button CSS class, like this:
$(".sports:checked").val();
Let's incorporate this concept into a larger example:
<script type="text/javascript">
$(document).ready(function() {
$("#survey").submit( function (eventObject) {
alert("Your favorite sport is " + $(".sports:checked").val());
eventObject.preventDefault();
});
});
</script>
</head>
<body>
<form id="survey">
<p>
<label for="name">What is your favorite sport?</label><br />
<input type="radio" name="sports" class="sports" value="racing" /> Auto Racing<br />
<input type="radio" name="sports" class="sports" value="football" /> Football<br />
<input type="radio" name="sports" class="sports" value="soccer" /> Soccer<br />
</p>
<input type="submit" name="submit" value="Vote!" />
</form>
Checkboxes are intended to give the user the option of making multiple selections. For instance, suppose your website offered several newsletters, and you wanted to give the user the opportunity to subscribe to as many as he pleased. You can use jQuery to determine which were selected like this:
...
<script type="text/javascript">
$(document).ready(function() {
$("#subscribe").submit( function (eventObject) {
var newsletters = "";
$(".newsletters").each( function() {
if ($(this).is(":checked")) {
newsletters = newsletters + "\n" + $(this).val();
}
});
alert("You've subscribed to the following newsletters:\n" + newsletters);
eventObject.preventDefault();
});
});
</script>
</head>
<body>
<form id="subscribe">
<p>
<label for="newsletters">Choose the desired newsletters</label><br />
<input type="checkbox" class="newsletters" value="video" /> The Video Summary<br />
<input type="checkbox" class="newsletters" value="podcasts" /> Weekly Podcast Update<br />
<input type="checkbox" class="newsletters" value="ebooks" /> The EBook Report<br />
</p>
<input type="submit" name="submit" value="Vote!" />
</form>
User Experience guru Jesse James Garrett's coinage of the term Ajax back in early 2005 rekindled interest in the JavaScript language. The realization that developers could use JavaScript in conjunction with standard markup formats and a server-side language to produce highly interactive, seamlessly updated websites sparked a flurry of advances which have greatly improved the overall user experience.
I recently published two extensive tutorials covering jQuery and Ajax (here and here), so rather than go to the considerable trouble of devising new examples I'll instead draw on what was covered in these tutorials for the next two examples.
You can use jQuery to communicate with a server-side language such as PHP to retrieve data stored in a database and seamlessly update a web site without forcing the user to reload the page. To do this however, you'll need to formalize the format in which the data is passed between the PHP script and calling JavaScript so jQuery knows how to parse this data. The most commonplace format for doing so is JSON. PHP conveniently offers a native function called json_encode() which can turn an array into JSON format. The following script (we'll call it books.php) demonstrates this process:
You can use jQuery's getJSON() method to contact the books.php script and parse the returned data, as demonstrated next. The returned values will be gathered and inserted into the DIV identified by the ID books.
$(document).ready(function() {
$("#button").click(function()
{
$.getJSON('books.php',
function(data) {
var textToInsert = [];
var i = 0;
var length = data.length;
for (var x = 0; x < length; x += 1) {
textToInsert[i++] = data[x].title + " (" + data[x].isbn + ")<br />";
}
$('#favorite-books').append(textToInsert.join(''));
}
)
return false;
});
});
...
<body>
<input type="button" name="button" id="button" value="Show My Favorite Books" />
<div id="books"></div>
</body>
See this blog post for a detailed explanation of this process.
Because the web is a two-way street, you'll also want to use Ajax to send data from the webpage, gathered within a form for instance, to the server. Using jQuery this is possible, although I also employ a jQuery plugin named jquery-json (more on jQuery plugins in the next section) to automate the conversion of a JavaScript array to JSON format.
The following example demonstrates the process of passing JSON-formatted data to a PHP script named addbook.php. Remember you'll need to download and reference the jquery-json plugin within the webpage for this example to work:
$("form#book-form").submit(function() {
var book = new Object();
// Retrieve the title and ISBN
book.title = $('#title').val();
book.isbn = $('#isbn').val();
// Use the jquery-json plugin to convert the form data to JSON
var bookJSON = $.toJSON(book);
// Contact addbook.php, passing in the JSON
$.post('addbook.php',
{book: bookJSON},
function(data) {
var ds = $.evalJSON(data);
if (ds.result == 1) {
$('#form-response').html("The book has been added to your collection.");
} else {
$('#form-response').html("Something seems to be wrong.");
}
}
)
return false;
});
The addbook.php script can retrieve and decode the posted $book variable like this:
$book = json_decode($_POST['book'], true);
$isbn = $book['isbn'];
$title = $book['title'];
Again, be sure to check out this blog post for a detailed explanation of this process.
With almost 3,000 plugins cataloged at http://plugins.jquery.com/, it's possible to extend jQuery in every imaginable fashion, whether you're looking for a way to add a cool image slideshow feature to your site, or are simply in need of a way to validate an e-mail address. I'll conclude this tutorial with an example involving one of my favorite plugins.
If you're publishing a particularly long essay or tutorial, you might consider breaking it down into several pages. Pagination is however a pretty tricky process, and you don't want to force the user to have to wait between page loads. jQuery to the rescue! Using Rik Lomas' great pager plug-in, you can automate the pagination process while simultaneously producing a slick navigational menu.

Figure 5. Paginating content Using the pager Plugin
To use this plugin, download it from the pager plugin website, and reference the plugin after you've referenced the jQuery library within your page's
tag.The following example paginates the content found in the article DIV according to paragraph:
...
<script type="text/javascript" src="/javascript/jquery.pager.js"></script>
<style type="text/css">
.nav { background: #eee; border-top: 1px solid #999; padding: 5px; }
.nav a { padding: 0 5px; }
</style>
<script type="text/javascript">
$(document).ready(function(){
$('#article').pager('p');
});
</script>
</head>
<body>
<div id="article">
<p>paragraph 1</p>
<p>paragraph 1</p>
<p>paragraph 1</p>
<p>paragraph 1</p>
</div>
...
Check out the pager plugin website for more information about this powerful plugin's many options.
Download all of the examples here
Jason's new book, "Easy PHP Websites with the Zend Framework", shows you how to build powerful websites using PHP, MySQL, and the Zend Framework. Included with each purchase is access to almost five hours of online video, a regularly updated PDF, and the opportunity to directly communicate with the author!
* (print book available in U.S. only)
Nobody has commented on this blog post yet. Why don't you be the first?
Only registered users can ask questions and post comments. If you're already registered login now. Don't have an account? Registering only takes a moment and it's free! Register now.
Have a question? Contact us!
News submitted by and about the PHP and Web development community.
Creating a Weather Forecast with PHP and the Google Weather API
Submitted by wjgilmore
How to Create an Image Gallery Powered By PHP and Picasa
Submitted by wjgilmore
Easy Databasing with SQLite
Submitted by wjgilmore
PHP IDE Roundup
Submitted by wjgilmore
Five Cool PHP Array Functions
Submitted by wjgilmore
Use jQuery with Greasemonkey
Submitted by wjgilmore
Encapsulation in PHP
Submitted by wjgilmore
Talking to Google Charts with PHP
Submitted by wjgilmore
Talking to Google Analytics with PHP
Submitted by wjgilmore
Building a jQuery/PHP-powered Chat Room
Submitted by wjgilmore
Cloud Computing with PHP
Submitted by wjgilmore
BattleMaster: A Web-based game written in PHP
Submitted by wjgilmore
Create an Image Rotator with CSS and jQuery
Submitted by wjgilmore
Copyright © 2009 W.J. Gilmore, LLC. All Rights Reserved. Purchase Policy · Privacy Policy
Trademarked names may appear on this website. Rather than use a trademark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to no benefit of the trademark
owner, with no intention of infringement of the trademark.