facebook google plus twitter
Webucator's Free jQuery Tutorial

Lesson: jQuery Intro

Welcome to our free jQuery tutorial. This tutorial is based on Webucator's jQuery Fundamentals Training course.

jQuery is a lightweight, powerful JavaScript library that simplifies the task of front-end scripting on web pages. This chapter introduces jQuery and shows a brief example of some of the library's capabilities.

Lesson Goals

  • Learn what jQuery is.
  • Use jQuery on your own sites.
  • Learn the reasons for the use of a ready handler when invoking jQuery code.
  • Learn some capabilities of jQuery by looking at a quick first example.

jQuery: An Introduction

jQuery is a library that simplifies and extends the use of JavaScript. As the documentation states, "[i]t makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript."

Since it is thoroughly tested - and in wide use - on a variety of browsers, because it is well documented, and because of the extensive collection of plugins that exist for it, jQuery makes the process of front-end web coding much simpler than using plain-old JavaScript. By using jQuery, we avoid having to worry about browser inconsistencies; can write shorter, easier-to-main code; and have access to useful, powerful widgets from other developers to make our work easier.

How jQuery Works

jQuery is a JavaScript library, written in JavaScript. Including the library on a web page offers you the ability to use all of jQuery's functionality. You might use it to manipulate a page's DOM (Document Object Model) elements, adding a background color to all divs of a given class, or inserting a new element at the top of a form based on a user's actions. You might use jQuery's Ajax (Asynchronous JavaScript and XML) capabilities to pull content from another page on your site or from an external feed like Twitter or Google.

We almost always include jQuery as a separate library. The custom jQuery code we write might also live in a separate JavaScript file, or might be on the web page itself; you will see examples of both throughout the course.

When including jQuery, you have the option of downloading it from the jQuery website and hosting it on your own site or you can link to it from a CDN (Content Delivery Network) where it is hosted for you. Consider these two examples:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<script src="/js/jquery-1.10.1.min.js"></script>

Both are examples of how we might include the jQuery library on a given web page. (Note that we would choose one or the other, but not both, of these options.) In the first case, we include jQuery from Google's CDN. The benefit here is performance - caching (your users' browser may already have cached that version jQuery from Google), increased parallelism (that is, avoiding the limits some browsers make on number of simultaneous downloads from one hostname), and decreased latency (given that Google's hosting is certain to be fast and, with many distributed servers, likely as not to be physically closer to your users than your hosting server), and the price (free) is pretty good to say the least. Using a CDN is generally the way to go.

The second case shows how you might link to the jQuery library that you download from the jQuery website and host on your own web server, in a directory named "js". The advantages here are that you have the code - it's on your site. You are not relying on an external provider - which could (though, in Google's case, that seems unlikely) go down - to serve a key part of your page.

Whichever strategy you choose, it is a good idea to use the minified version of jQuery; note the "min" in the file names in the examples above. Minification is the process of stripping whites pace and using shorter identifiers for variable and function names, significantly cutting down the size (and thus the download time) of the file. The minified version works exactly the same as the un-minified version; it's best to use the minified version for production sites.

Running Code on Document Ready

Often we will wrap our jQuery code in the ready handler. This ensures that the jQuery code we write does not execute until the DOM has loaded but (usefully) does not wait until all images have downloaded.

Here's a quick example:

$(document).ready(function() {
	$('a.thanks').click(function(event) {
		alert("Thanks!");
	});
});

We attach a click handler to any a tag (i.e., a link) of class thanks; users who click on any such link will see a JavaScript alert (a popup) with the text "Thanks!". Wrapping the code in the ready handler ensures that the handler is active as soon as the page's DOM has loaded, but not after all images have loaded. We will cover this concept in more detail later in the course.

A First Example

Let's look at an example of what one might do with jQuery. Note that the code here is fairly advanced; while we will cover the specifics in detail later in the course, for now let's consider this an overview of the power of jQuery.

Open ClassFiles/jqy-new-intro/Demos/index.html in a browser and in a code editor to review the code. The page displays a map of the world with two links marking New York City ("NYC") and London ("LON"):

Map of World Image from Wikipedia Wikipedia

Mousing over either of the cities expands the containing element, which has a semitransparent red background, and display some details - area, population - about the city:

Map of World

Let's look at the code.

Code Sample:

jqy-new-intro/Demos/index.html
---- C O D E   O M I T T E D ----

<body>
<div id="world">
	<div id="nyc" class="city">
		<a href="#" class="citylink">NYC</a>
		<div class="details">
			<p><strong>New York City</strong>
			<br>Area: 468.5 sq mi
			<br>Population (2012 est): 8,336,697
			<br>Source: <a href="http://en.wikipedia.org/wiki/New_York_City">Wikipedia</a></p>
		</div>
	</div>
	<div id="lon" class="city">
		<a href="#" class="citylink">LON</a>
		<div class="details">
			<p><strong>London</strong>
			<br>Area: 1,572.00 sq km
			<br>Population (2011): 8,173,194
			<br>Source: <a href="http://en.wikipedia.org/wiki/London">Wikipedia</a></p>
		</div>
	</div>
</div>
<script>
	//ready handler: run this code after the DOM is loaded..
	$(document).ready(function() {
		$('.city').hover(
			//when the user's mouse enters any .city div..
			function() {
				//change the width and height (bigger),
				//over 1000 miliseconds,
				//and show the contained .elements div
				$(this).animate({
					'width': '300px',
					'height': '105px'
				},
				1000,
				function() {
					$(this).find('.details').show();
				});
			},
			//when the user's mouse leaves any .city div..
			function() {
				//change the width and height back to original values,
				//over 1000 miliseconds,
				//and hide the contained .elements div
				$(this).animate({
					'width': '50px',
					'height': '40px'
				},
				1000,
				function() {
					$(this).find('.details').hide();
				});
			}
		);
	});
</script>
</body>
</html>

We use a div of class city to mark up each city's info. Each div is positioned absolutely and is, initially, 50px by 40px in size.

We wrap our jQuery code in a ready handler, to ensure that it runs after the page's DOM has loaded. We use jQuery's hover event to attach a handler to any element of class city. The first function contained within hover states what happens when the user mouses into the element; the second function states what happens when the user mouses out of the element.

When the user's mouse enters, we change the width and height of the appropriate div with jQuery's animate method, making the div bigger over the course of 1000 milliseconds, and show the div of class details. Similarly, we animate the div back to its smaller size and hide the div of class details when the user mouses out.

Again, please do not worry about the specifics of the code here; we will cover all of it in detail as we move through the course. Hopefully, you see the power of jQuery: how easy it is, with just a few lines of code, to produce complex, interesting effects and interactions.