Tallan's Technology Blog

Tallan's Top Technologists Share Their Thoughts on Today's Technology Challenges

jQuery Part 2: More jQuery Basics

Dylan Barrett

Introduction

Welcome to the second part of my overview of jQuery. This article is part of a 3 part series. If you did not read the first article, you may want to go back and read that first. This article is going to pick up where the last article left off and cover more jQuery basics. Specifically, the events and effects functionality will be discussed. Afterwords, I will show some example code that utilizes many of the techniques that we have learned.

Events

Event handling can sometimes be a problem when developing cross-browser applications. There are often at least two different ways of doing things depending on which browser is being used. jQuery helps us by abstracting the event handling logic. Behind the scenes jQuery will use feature detection to figure out which browser the code is being run on and then utilize the appropriate functionality for the specific browser. The user of the library is presented with a single, clean, unified API that they can use to add event handling to any element on the page in a cross browser fashion. The first of these functions that I am going to cover is the bind function. This function accepts two arguments; a string containing the type of event, and a function to handle the event. Multiple event handlers can be bound to an element this way. Here is an example:

$('#myButton').bind('click', function() {
  $('p').css('color', 'red');
});

This code finds the element with an id of “myButton” and adds an event handler to it. The handler, when the element is clicked, will find all paragraph elements and make their text a red color. If you wish to remove an event handler from an element, you can use the unbind function. There are many useful overloads of the function. If you pass it no parameters then it will remove all events from the selected elements. If you pass it the name of the event it will remove all handlers for that event type. If you pass it the name of the event and the handler function it will remove only that handler from the element. If we run the follow code then the button will no longer respond to the click event we set up previously.

$('#myButton').unbind('click');

jQuery also provides shortcuts for most of the events. Instead of using the bind function you can use a specialized event function. An example of this is the click function. It takes a handler function as its sole argument. Here is a copy of the above code using the click function instead of bind:

$('#myButton').click(function() {
  $('p').css('color', 'red');
});

All event handlers can optionally take in an argument of the event object. The event object also has cross browser differences. jQuery creates a cross-browser version of the event object for us to use in our handlers. The details of this object are described on the jQuery website.

Effects

Another cool feature of jQuery is its support for effects. jQuery provides a handful of simple effects out of the box, but allows for extending the library by adding new effects. We will cover a couple effects in this article. The hide and show effects can be used to make elements on the page appear and disappear. At their simplest they take no arguments, and when called simply make the element appear or disappear from the page. You can also pass them a number specifying the milliseconds that the effect should take. When a number is provided, the element will shrink in size while also becoming transparent until it disappears from the screen if using hide, or will appear on the screen and grow in size and opacity if using show. Here is a demo:

$('img.hideable').click(function() {
  $(this).hide(2000);
});
$('#myButton').click(function() {
  $('img.hideable').show();
});

This demo selects all images with class “hideable” and assigns a click handler to them. If they are clicked on the will disappear from the screen over a two second interval. Because a time is given the image will shrink and become transparent over the time period. A click handler is also assigned to a button. When clicked it will make the image appear on the screen (if hidden). It is not passed a number so it will appear instantly. Another useful function is the toggle function. When used it will cause an element to appear if hidden, or disappear if visible. It also can take a time value. It is demonstrated below:

$('#myButton').click(function() {
  $('img.magic').toggle(3000);
});

When the button is clicked the images with class “magic” either appear or disappear, depending on their current state. There are other available effects such as slideUp, slideDown, fadeIn, and fadeOut. If you wish to make more complex animations you can use the animate function which allows very fine control. You can read about all of these on the jQuery website and many other effects exist on the plugins page of the site.

Example

Now it is time to look at a complete example. You can download a zip file containing all of the source code here. In this example we are going to create a simple page containing nested lists. The levels of the list will be able to expand or collapse when clicked on. If there is no sublist under the current list element, then clicking on the element will do nothing. Here is the code for the HTML page:



<script src="jquery-1.4.2.min.js" type="text/javascript">// <![CDATA[
    
// ]]></script>
<script src="jQueryExample1.js" type="text/javascript">// <![CDATA[
    
// ]]></script>

</pre>
<h1>jQuery Part 1 Example</h1>
<pre>
Here is a list containing other nested lists.
 We can use jQuery to hide or show the list
 elements.</pre>
<ul>
	<li>jQuery Part 1: The Basics
<ul>
	<li>Introduction
<ul>
	<li>What is jQuery?</li>
	<li>Where to Get jQuery</li>
</ul>
</li>
	<li>Core jQuery
<ul>
	<li>Selectors</li>
	<li>The Wrapped Set</li>
	<li>The jQuery Function</li>
	<li>Traversing the DOM</li>
	<li>Manipulation
<ul>
	<li>Attributes</li>
	<li>CSS</li>
	<li>Other</li>
</ul>
</li>
</ul>
</li>
	<li>Events</li>
	<li>Effects</li>
	<li>Example</li>
	<li>Conclusion
<ul>
	<li>Summary</li>
	<li>Want To Learn More?
<ul>
	<li>Next Article</li>
	<li>jQuery.com</li>
	<li>jQuery In Action</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<pre>

And here is the JavaScript code for the example:

$(function() {
  $('li > ul').hide().each(function() {
    var sublist = this;
    $(this).parent().addClass('collapsed').click(function(event) {
      if (this == event.target) {
        $(this).toggleClass('collapsed expanded');
        $(sublist).toggle(1000);
      }
    });
  });
  $('li:not(:has(ul))').removeClass('collapsed
                                     expanded').addClass('leaf');
});

You will see that the HTML for the example is very clean. All styles are in an external stylesheet (not shown, but included in the download) and all the Javascript is in a separate file. The jQuery code starts with the jQuery function setting up a function to be run when the page is ready. We first select all of the ul elements on the page that are children of li elements. These are the sublists. We call the hide function to immediately hide the sublists. Next we use the each function to run code on each element of the wrapped set. The first thing we do inside of the each is set a variable called sublist to the current element (using ‘this’). This allows us to create a closure to access the element from within event handlers defined below it.

Next, we get the parents of the wrapped set elements and make a wrapped set out of them using the parent function. This set contains the li elements that the sublists reside in. We then add a class called “collapsed” to the li elements. This refers to a style declared in the external stylesheet that makes the bullet for the li element into a plus sign. This makes it easier to see that the list can be expanded at this point. We create a click handler for the li elements which first check if the element handling the event is the actual element that was clicked. This is done to ensure that no other elements respond to the event when the event is bubbling up or down the DOM. Next we use the toggleClass function to set the class to either collapsed or expanded. We also use the toggle function to toggle the visibility of the sublist of that element. Finally, in a completely new jQuery statement, we select all li elements that do not contain sublists. We remove any existing collapsed or expanded class and add the leaf class to them. This replaces the bullet for the list element with an empty circle. This shows that there is no sublist below this node.

That’s it! In this small about of code we were able to create some pretty cool functionality. I suggest that you download the code and try it out for yourself. Tweak the code to see what else you can do with it. Have fun!

Conclusion

That is all that I am going to cover in this article. We learned about how jQuery handles events as well as how to create some cool effects to liven up your page. Finally, we went through an example that brought everything we learned together.

Want to Learn More?

The next and final article in this series will cover some advanced jQuery functionality. I will be covering the topics of ajax, utilities, and plugins, as well as another exciting example! Again, keep in mind that I am only covering a very small subset of what is available in the jQuery library. I suggest you check out the jQuery documentation page at jQuery.com. The documentation for jQuery is excellent and provides many useful examples. I also recommend jQuery In Action by Bear Bibeault and Yehuda Katz. It is an excellent book and worth checking out. I hope you enjoyed this article. The next part should be out within the next couple of weeks.

-Dylan

Tags: JavaScript, jQuery,

1 Comment. Leave new

Great. there is the part 2. I would like to waiting for jquery function

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

\\\