jQuery Quick Tutorial

November 14th, 2011 Leave a comment 1 comment
Like the article?
jQuery Quick Tutorial

Whether you are new to JavaScript or have been developing for the Web for a while, learning jQuery can seem like a daunting task. If you have been wanting to give it a try, here is a quick primer to give you the facts and help you get started along with some examples for you to try out.

If you want to play with the examples from this tutorial, feel free to download them from here.

What is it?

jQuery was originally developed by John Resig of the Mozilla Software Foundation in 2006 with the motto of “Write less, do more”. It was originally intended to be a way of creating cross-browser support for DOM scripting but it has become far more than that. So, why all the confusion? jQuery is not a scripting language in and of itself, it is a companion library and toolkit that is used with JavaScript that allows for your applications to be developed quicker and with richer features such as animation effects, interactivity and UI elements.

Why should I use it?

jQuery will not only allow you to create your applications quicker but it has created a way for you to reuse light-weight and robust elements that save you time coding and testing, ultimately resulting in smaller, better-made code. This also means that several tasks that would be complex have been made simple and within the reach of the new or casual developer.

jQuery currently supports all major browsers and works to maintain a high level of cross-browser support. You can use it in IE 6.0+, Firefox 2.0+, Safari 3.0+, Chrome and Opera 9.0+. It also has internal AJAX support and offers a large amount of support for events and DOM manipulation.

How do I get started?

jQuery does not require a lot of setup or installation. Following these simple steps will get you ready to use jQuery:

  1. Go to the jQuery homepage page:Click “download” at the top of the page and scroll down to the section titled “Current Release”. This is the latest stable release of jQuery and the one recommended for you to use.
  2. You can choose either the packed version named jquery-version#.js or the minified version which is recommended if you will be using it in a production environment. Minified versions are named jquery-version#.min.js.
  3. Once downloaded, save the file in a directory of your Web site so you can access it from your site pages.

NOTE: As an alternate (and often preferred) method, you can just directly reference the latest jQuery library from the Google Libraries API website by embedding the following code in your web pages:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>

That’s it! jQuery is now ready to be called from your HTML pages and JavaScript files and used to write new scripts. No other installation is required!

How do I use it?

To begin using your new jQuery library, you simply include the jQuery .js file (named after your jQuery version) in your HTML document like you would any other external js file. For example:

<html>
	<head>
		<title>jQuery Quick Primer</title>
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>

		<script type="text/javascript">
			// other javascript code goes here
		</script>
	</head>

	<body>
		<!-- HTML content goes here -->
	</body>
</html>

Once you have the file being loaded in you can begin to call some of the functions of jQuery. One of the first library function calls you should learn is the $(document).ready() function. This function waits to process your script until the DOM is ready to receive your instructions. Since almost everything in jQuery works with DOM objects, waiting until the DOM is ready is good practice and prevents errors or failures in your application. Here is an example of how to call the $(document).ready() function:

<html>
	<head>
		<title>JQuery Quick Primer</title>
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>

		<script type="text/javascript">
			$(document).ready(function() {
				// code executes when DOM is ready
			});
		</script>
	</head>

	<body>
		<!-- HTML content goes here -->
	</body>
</html>

As you can see, any code we want to execute when the DOM is ready can go into this function. The dollar sign ($) is used in jQuery as an alias for a jQuery selector. Most function commands and events will begin with the dollar sign in your code. $(document) says to select all items in the document, so we can run the ready() function for all of them.

What are some ways I can use jQuery on my site?

jQuery has many practical uses from eye-catching animations to navigation, menus, modal popups and more. Here are a few examples of how you can use jQuery to spice up your site. Note that for these I am only going to show the code required for each step, look at the commented sections of the code above to know where to put them.

Sliding elements:

Sliding elements are a great way to get the user’s attention and to present information or forms such as newsletter sign up boxes or to expose more information to the user on demand. jQuery has several functions to handle sliding animations:

  • .slideDown() – Moves the element down the page vertically to a new location (or appear)
  • .slideToggle() – Used to display or hide the element with the sliding effect
  • .slideUp() – Moves the element up the page vertically to a new location (or hide)
To create this effect it will require several small pieces of JavaScript with jQuery along with some CSS. We’ll start with the HTML:
<input type="button" id="click_me" value="Click for more info">
<div id="moreInfo">
	<a href="#" class="close">[X]</a>
	<p>Here is the more info you requested.  Click on the [X] to close this window.</p>
</div>

So what we have done with the HTML is create the elements the user will see so they can interact with the page. The button we created will be our point of entry for the information box. The div holds the information box as well as an anchor tag that will trigger the box to close.

Next some CSS:

<style type="text/css">
#moreInfo {
	display: none;
}
</style>

This CSS ID selector is needed so that the information box text is not visible to the user when the page is first loaded. Our jQuery script will take care of showing and hiding it from here. Of course you could always spice up the information box and/or the button with more CSS but this is the bare minimum needed. Now for the jQuery. We’ll take this step by step:

$("#click_me").click(function(event) {
	event.preventDefault();
	$("#moreInfo").slideToggle();
});

This function listens for the click of the #click_me button. When the button is clicked by the user, this function will fire and prevent the default behavior of the button. Instead it will call the .slideToggle() which will open or close the information box based on its current state.

$("#moreInfo a").click(function(event) {
	event.preventDefault();
	$("#moreInfo").slideUp();
});

This function listens for the click of the anchor tag within the #moreInfo div container. When clicked, it will prevent the default behavior of the anchor element and instead will all the .slideUp(), which will cause the information box to animate the hide action. There is no need for a matching .slideDown() function since the .slideToggle() will take care of that for us.

That is all that is needed to create a slick-looking information box that rolls down at the click of the button and back up at the click of the anchor.

A Modal Window:

A modal window or popup has many uses such as a login box, newsletter sign-up, notice or sticky note. Since the modal window forces the user to pay attention to it by taking over the current window the user has to attend to the window before they can go back to the page. Here is a short demonstration on how to make your own modal window.

First, the HTML:

<a href="#modalBox" name="modal">See my modal box</a>

<div id="boxes">
	<div id="box" class="box">
		<h3>Text of my modal box</h3>
		<a href="#" class="close">Close Box</a>
	</div>

	<div id="mask"></div>
</div>

OK, so the idea here is to create a link that can be used to open the model box. That is the purpose of the first anchor. Inside the “boxes” div are two other divs. The “box” div is the modal popup itself. You can customize your modal popup with a background image, colors and whatever text or form elements you would like in the CSS. The second div serves a different purpose. Its job is to “mask” the rest of the page when the modal is active so the rest of the page appears to be inactive. Next, the CSS:

#mask {
	position: absolute;
	left: 0;
	top: 0;
	z-index: 9000;
	background-color: #000;
	display: none;
}

#boxes .box {
	position: absolute;
	left: 0;
	top: 0;
	width: 44px;
	height: 200px;
	display: none;
	z-index: 9999;
	padding: 20px;
}

#boxes #box {
	width: 375px;
	height: 203px;
	background-color: #ffffff;
}

The CSS rules for the mask should be obvious to its task: make the rest of the page unusable while the modal is active. You have to make the mask’s z-index lower than the boxes window or it will take out the modal window with it. The second selector chooses the box div from the boxes, the one that becomes the modal window. This will position it correctly in the middle of the screen and above the “inactive” portion of the page. The last rule sets the style for the box itself. If you are going to customize the modal window this would be the place to put it.

Finally, the script:

$(document).ready(function() {
	$("a[name=modal]").click(function(event) {
		event.preventDefault();
		var id = $(this).attr('href');

		var maskHeight = $(document).height();
		var maskWidth = $(window).width();

		$("#mask").css({
			'width': maskWidth, 
			'height': maskHeight
		});

		$("#mask").fadeIn(1000);
		$("#mask").fadeTo("slow",0.8);

		var winH = $(window).height(); 
		var winW = $(window).width(); 

		// Set the popup window to center 
		$(id).css('top',  winH / 2 - $(id).height() / 2); 
		$(id).css('left', winW / 2 - $(id).width() / 2); 

		// transition effect 
		$(id).fadeIn(2000);  
	});
});

This function sets up the behavior for the mask portion of the effect. It finds the tag named “modalBox” and then finds the anchor tag inside of it. It finds the screen height and width so the mask can be calculated to fill the entire screen. Finally it gets the window height and width to help center up the modal window and sets up the fadeIn() transition effect.

$(".box .close").click(function(event) {
	event.preventDefault();
	$("#mask").hide();
	$(".box").hide();
});

$("#mask").click(function() {
	$(this).hide();
	$(".box").hide();
});

This first function handles the close event for the modal window. When the event to close the box is called this function will prevent the default behavior and instead use the hide() function to remove the box from view. The second function hides the mask and the modal window if the user clicks off into the mask area, trying to return to the page.

While this marks the end of our jQuery Quick Primer, hopefully it has inspired you to get started writing your own jQuery scripts and begin to get familiar with the different functions and effects that the library has to offer. You can find full documentation on the jQuery library along with explanations of different functions and examples at http://www.jquery.com.

Article Source Files

DescriptionNameSizeDownload method
jQuery Quick Tutorial Source Codejquery-quick-tutorial.zip35KBHTTP
Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
Don't miss another post! Receive updates via email!
  1. Tom Mags says:

    A Modal Window works fine in IE8, but does not appear to work with Firefox ?

Comment