Login | Register | FAQ
Anonymous


Lesson 19: Short Introduction to jQuery

By Maria Antonietta Perna

You've come a long way in your JavaScript journey. Now it's time to get to the fun part.

This lesson, together with the next 2 lessons, will introduce you to jQuery, the fantastic JavaScript library invented by John Resig.

However, this is a wide topic and these 3 lessons cannot but give you just a taste for what jQuery can really do.

Therefore, I encourage you to visit the jQuery website after you finish this tutorial, and explore and experiment with jQuery's numerous methods, events, effects, etc., for yourself.

In this lesson you will learn:

  • about the benefits of using jQuery;
  • how to include jQuery in your project;
  • about jQuery selectors to manipulate DOM elements in code;
  • how jQuery handles events;
  • how to use anonymous functions with jQuery;
  • how to add and remove DOM elements with jQuery.

Why should I use jQuery?

Here are some good reasons why using jQuery in your JavaScript projects is a great idea.

jQuery is:

  • extremely light-weight (just 31 kb in its latest minified and zipped production-ready version);
  • it's free and very easy to include in your projects: just download its latest version from the jQuery website, or use an online Content Delivery Network;
  • it's continually upgraded, maintained and documented by a dedicated community of great developers. This ensures high quality and support on the internet;
  • it helps overcoming inconsistencies in the way some JavaScript features are implemented across different browsers;
  • and last but not least, it offers a wealth of ready-made animation effects that are a joy to use.

How do I include jQuery in my website?

Including jQuery in your project is fast and easy. You have the choice of downloading a copy of the library and save it locally, or you can use a Content Delivery Network (CDN) to serve jQuery to your website on the Internet.

Go to the jQuery website download page

How to include a local copy of jQuery

If you prefer having a local copy of jQuery:

  1. go to the Download jQuery section of the download page and click on the minified version of the latest release of jQuery. At the time of writing this is version 1.7;
  2. copy and paste the code in a text file;
  3. save the file in your web project directory (better if you save it in its own subfolder);
  4. in your html page include the appropriate <script> tags in the following order:
		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 19: Introduction to jQuery</title>
		
		<script type="text/javascript" src="js/latestjquery.js"></script>
		
		<script type="text/javascript" src="js/yourscript.js"></script>
		
		</head>
		<body>
		<h1>Lesson 19: Introduction to jQuery</h1>
			
		</body>
		</html>
		
		

The reference to jQuery comes before your own JavaScript code file. In fact, your code needs to find jQuery already fully loaded to be able to use it.

How to include a hosted copy of jQuery

If you decide to opt for a CDN to serve up a copy of jQuery to your website, then follow these easy steps:

  1. go to the CDN Hosted jQuery section of the download page and pick one of the different CDN services available;
  2. copy the URL of your CDN of choice and paste it as the value of the <script> tag's src attribute, like so:
    <script type="text/javascript" src"yourCDNUrlAddressjQueryFile.js"></script>
  3. place a <script> tag with a reference to your own JavaScript file underneath the jQuery <script> tag, like you did in the previous example.

That's it, you're done!

How to make sure jQuery is working

Now the jQuery library can be used in your project. To make sure things work as expected, create a text file and call it jquery_test.js. Enter the following code:

		
		//Most of your code goes inside
		
		//the jQuery ready() function:
		
		$(document).ready(function()
		
		{
		
		alert("jQuery is working!");
		
		});
		
		//Make sure you keep track of braces, brackets, and semi-colons ( ; )
		
		

Save all your files and run the HTML page in a browser. If you typed the code exactly like the example above, you should be greeted by ... well, the good old alert box.

The $ sign is an alias for jQuery. You could replace it with the keyword jQuery and your jQuery-powered JavaScript code would work just fine. However, less typing is jQuery's (and all coders') motto, so using $ is the accepted convention.

.ready(function() { //JavaScript code here ... } );

is where most of your JavaScript code will be placed. This is jQuery's clever way of making sure your code runs when the document is ready for it: that is, when the html is fully loaded.

How do I access DOM elements using jQuery?

jQuery appeals so much to web designers also because it enables us to select DOM elements in code just like we do with CSS. Let's see it in action.

Select html elements by id

Remember our old document.getElementById()? Well, jQuery makes selection by id much shorter. Here's how it's done:

		
		$(document).ready(function()
		
		{
		
		var myDiv = $("#myDiv");
		
		});
		
		

The $ sign in front of ("#myDiv") can be translated like: "Hey, browser, get me the element with the id of myDiv!"

As you can see, the id attribute is grabbed by using the # sign, the same as CSS.

Select html elements by tag name

You also came across document.getElementsByTagName(). This method allows us to grab all html elements by their tag.

Look how jQuery makes it a lot snappier:

		
		$(document).ready(function)
		
		{
		
		//store all images on the page in an array
		
		var images = $("img");
		
		});
		
		

As you can see, the magic $ does most of the talking.

Select html elements by class name

A quick way to target html elements that share the same class is as follows:

		
		$(document).ready(function()
		
		{
		
		var redElements = $(".classRed");
		
		});
		
		

Now redElements contains an array of all the html elements on your page with a class of classRed.

Once again, notice how jQuery facilitates selection by using the same notation you use in your CSS declarations to target classes: .className.

Select html elements using jQuery filters

jQuery enables you to be as precise as a surgeon when targeting html elements and attributes on the page. jQuery offers a filtering syntax to query the DOM that is both simple and efficient.

Here's a list of the most common filters:

Filter Description
:first The first item in a matched set
$(‘p:first’) returns the first paragraph.
:last The last item in a matched set
$(‘p:last’) returns the last paragraph.
:odd The odd-indexed items in a matched set
$(‘tr:odd’) returns table rows indexed at 1, 3, etc.
:even The even-indexed items in a matched set
$(‘tr:even’) returns table rows indexed at 0, 2, etc.
:has finds elements having the child element specified
$(‘p:has(span)’) returns all paragraphs containing a span element.
:eq returns the element with the matched index
$(‘p:eq(1)’) returns the second paragraph starting to count at 0.
:contains(x) Returns all elements containing the text x
$(‘div:contains(foo)’) targets all divs with the text 'foo'.

A complete list of all selection methods and filters is available on the jQuery website. Have a look and experiment with the available code samples to gain more familiarity with the new approach.

How do I assign event handlers using jQuery?

Event handlers are code blocks, usually functions, that specify what your application should do when a specified event like, for example, a button click, occurs.

So far, you've used 2 approaches:

  1. hard-wiring a function to the html element itself: <input type="button" onclick="doSomething()" />
  2. assigning a function to the DOM object's appropriate property: myElement.onclick = doSomething;

Both approaches are fine. However, the first one sins against the separation of concerns principle. In fact, it mixes in JavaScript code with HTML code.

The second approach complies with the separation of concerns principles, but comes short in case we want to attach more than a function to the same element.

There's actually a third approach that overcomes all shortcomings but one: it's implemented differently in Internet Explorer browsers with respect to all other major browsers.

The good news is: jQuery is here to make event handling quick and easy. Here are a few jQuery approaches to choose from.

The bind() method

bind(eventType, handler) works as follows.

Suppose you have an html element with an id of myElement, and a function called sayHello(). You want sayHello() to kick in when the user clicks on the html element. This is how you achieve this using bind():

		
		$(document).ready(function()
		
		{
		
		//create the sayHello function
		
		function sayHello()
		
		{
		
		alert("Hello jQuery");
		
		}
		
		//Attach the handler using .bind():
		
		myElement.bind('click', sayHello);
		
		});
		
		

You can find more details on the bind() method on http://api.jquery.com/bind/.

The ready-made approach

jQuery offers some ready-made handlers corresponding to JavaScript events. Here's a list of the most widely used ones:

Handler Description
click() Binds a handler to an onclick event.
hover() Binds a handler to the onmouseover and onmouseout events.
change() Binds a handler to the onchange event (when the content of a field changes).
select() Binds a handler to the onselect event (when text is selected).
submit() Binds a handler to the onsubmit event of a form element.
focus() Binds a handler to the onfocus event (when an element gets focus).
keypress() Binds a handler to the onkeypress event (when a key on the computer keyboard is pressed).

Assuming you have an html element with an id attribute of myElement, and a function called sayHello() - as in the previous example - you can bind sayHello() to the onclick event of myElement inside jQuery's ready() function like so:

		
		myElement.click(sayHello);
		
		

The on() method

With this latest version of jQuery (v.1.7), a brand new method to handle events has been introduced.

The on() method is highly recommended by the jQuery team if you start a new project.

It can be used to attach handlers both to elements already present in the HTML page from the start and on dynamically added elements (unlike bind()). Here's how it's used.

Using the same sayHello() function, inside jQuery's .ready() function simply write:

		
		myElement.on('click', sayHello);
		
		

More details on the on() method can be found on http://api.jquery.com/on/.

Anonymous functions

Code samples using jQuery often employ anonymous functions. These are functions without a name, and can be quite handy, although I find names more helpful in terms of code readability. If we replace the sayHello() function with an anonymous function, we have:

		
		//Using bind():
		
		myElement.bind('click', function()
		
		{
		
		alert("Hello jQuery");
		
		});
		
		
		
		/********************************/
		
		
		
		//Using click(), we have:
		
		myElement.click(function()
		
		{
		
		alert("Hello jQuery");
		
		});
		
		
		
		/**************************************/
		
		
		
		//Using on(), we have:
		
		myElement.on('click', function()
		
		{
		
		alert("Hello jQuery");
		
		});
		
		

Add and remove DOM elements

Once grabbed by your JavaScript code, DOM elements can easily be manipulated with jQuery.

You've had a taste of standards-compliant DOM manipulation techniques in this tutorial. Therefore, you will readily appreciate the jQuery way of performing the same tasks.

Add new DOM elements

You can both retrieve html elements and add new html elements to the page using jQuery's .html() method. When you don't pass any arguments, html() retrieves a DOM element, if you pass a string argument, html() adds that string to the page.

If you just need to add new text inside an html element, you can use jQuery's .text() method and pass a string argument representing the text you intend to add. Like .html(), you can use .text() without passing any arguments to retrieve text content from the HTML page.

To test .html() prepare an HTML page containing a <div> tag with an id of myElement, a <p> tag and some text. First we retrieve the existing paragraph element, then we create a new paragraph.

		
		$(document).ready(function()
		
		{
		
		//Use html() to retrieve content:
		
		var pageParagraph = $('p').html();
		
		//the alert should display <p>'s content
		
		alert(pageParagraph);
		
		});
		
		
		/**************************************************/
		
		
		//Now let's change the div's content
		
		//by adding a new paragraph.
		
		var newParagraph = $('#myElement').html('<p>Hello new Paragraph!</p>');
		
		//close off all your brackets:
		
		});
		
		

Save all your files and preview the result in a browser. The alert should display the original paragraph's content, and the page should subsequently display the new paragraph's content.

The way you implement .text() is the same as .html(). I leave you to experiment with it on your own. More details on .html() can be found on http://api.jquery.com/html/, and on .text() can be found on http://api.jquery.com/text/.

Remove DOM elements

A simple way of doing this is with jQuery's remove() method. Let's put it to the test.

Use the same HTML page from the previous example and add a button element with an id of btnDelete.

In a fresh JavaScript file, add the following code:

		
		$(document).ready(function()
		
		{
		
		//use a click handler and an anonymous function
		
		//to do the job
		
		$('#btnDelete').click(function()
		
		{
		
		//delete all <p> elements
		
		$('p').remove();
		
		});
		
		});
		
		

Save all your files and preview the HTML page in a browser. Click the button and see the paragraphs on the page disappear.

More on .remove() can be found on http://api.jquery.com/remove/.

Summary

There's a lot to digest in this introduction to jQuery and you've done a great job coming as far as you did.

jQuery is such a rich library that it can't be covered in a few lessons. Therefore, I invite you to practice with all the code samples in this lesson and the following lessons as much as you can.

Also, it's crucial that you explore the jQuery website and experiment with the code samples available in their documentation and tutorials. If you have doubts, don't hesitate to send us a line in the forum dedicated to this tutorial.

More on jQuery coming up in the next lesson: get ready for some fabulous JQuery effects in just a few lines of code!


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 18: Making AJAX Calls

Lesson 20: Cool Animation Effects with jQuery >>

?>