Ads 468x60px

Labels

Wednesday, May 2, 2012

Sliding elements

In the previous chapter, we saw how we could fade elements in and out of visibility using the fading methods of jQuery. However, sometimes a sliding effect is a better choice, and for that, jQuery has a set of matching methods for doing just that. Let's kick off with a simple example of it, where we use the slideDown() method:

Show box

Fading elements

Doing simple animation is very easy with jQuery. One of the effects it supports out-of-the-box, is fading an element in and out of visibility. Here's a simple example, where we fade in an otherwise hidden box, using the fadeIn() method:

Show box

Working with widths and heights

jQuery makes it easy for you to work with the dimensions of your elements and even the browser window. You can use the width() and height() methods for finding the dimensions, or alternatively the innerWidth()/innerHeight()/outerWidth()/outerHeight() methods, depending on the measurements you need. First a little example illustrating the differences and the some explanation:
Show element dimensions

The live() method

In the previous chapters, we used the bind() and unbind() methods to attach and detach event handlers to various elements on the page. This works great for elements which already exists, but what if you want your event handler to be attached to future elements as well? Normally you would have to do this manually, upon creating the new elements, and this is still possible. However, using the live() method, you can inform jQuery to attach your event handler to any future elements which matches your original selector, without having to lift a finger. Let me first show you an example where we use the bind() method, and then replace it with the live() method, to show you the difference:
Add box
This is a box

The unbind() method

In the previous chapter, we used the bind() method to subscribe to events with jQuery. However, you may need to remove these subscriptions again for various reasons, to prevent the event handler to be executed once the event occurs. We do this with the unbind() method, which in its simplest form simply looks like this:
$("a").unbind();
This will remove any event handlers that you have attached with the bind() function. However, you may want to only remove event subscriptions of a specific type, for instance clicks and doubleclicks: $("a").unbind("click doubleclick"); Simply separate the event types with a comma. Here is a more complete example, where you can see it all in effect:
Test 1
Test 2

 

The bind() method

One of the most important aspects of dealing with events through jQuery is the bind() and unbind() methods. As the names imply, they will simply attach and unattach code to one or several events on a set of elements. We saw a very simple usage example for the bind() method in the introduction chapter for events, and here is a more complete one: Try this example Test 1 Test 2 It works by selecting all links ( elements) and then bind the anonymous function you see to the click event. A cool little feature is that jQuery will automatically assign the element that is clicked, to the "this" keyword inside of the anonymous function. This will allow you to access the element that activates the element, even when you assign the same code to multiple elements. When jQuery calls your method, it will pass information about the event as the first parameter, if you have specified one or more parameters on it. For instance, the event object passed will contain information about where the mouse cursor is, which type the event is, which keyboard key or mouse button was pressed (if any) and much more. You can see all the properties and methods on the event object here: http://api.jquery.com/event.which/ Here is an example:

Introduction to events

Events in JavaScript are usually something where you write a snippet of code or a name of a function within one of the event attributes on an HTML tag. For instance, you can create an event for a link by writing code like this: Try this example
Test
 

Aborting an AJAX request

There may be situations where you need to cancel a running AJAX request before it ends. It's usually in cases where the user might perform an action, which sets of an AJAX request, several times within a short time period. A good example of this is auto-complete functionality for a search box, where you might try to help the user by finding related search terms based on their current input, by making an AJAX request each time they press a key in the search field. In that case, it's very likely that the user types faster than your AJAX request can be performed and therefore you would want to abort any non-finished requests, before starting the next one. Consider the following example:


It requests a PHP script which is doing a very complicated calculation (as you will see from the result), which means that it usually takes ~3 seconds to finish. Now, try the example and push the button several times after each other. The same "calculation" will be performed multiple times and the result will also be displayed multiple times (with a 3 second delay). Fortunately, a call to the get() method and pretty much any other jQuery AJAX method, returns an object which, among others, contains an abort() method. We can save this reference and then call the abort() method on it if needed. Have a look at this slightly modified example:


We start off by defining a common variable for containing the request reference. In the PerformAbortableCalculation() method, we assign the return value of the get() call to this variable, but before we do so, we check to see if it's null (the method hasn't been used yet) and if not, we call the abort() method on it. If you try this example and click several times, you will see that no matter how many times you click the button, it only executes the callback function once.

Showing progress

When doing AJAX requests, you may want to show some sort of progress while waiting for the request to finish, especially if it might take a while for it to do so. It's actually very simple to do so with jQuery, as you will see from the following example:



Right before performing the AJAX request, we change the text of the sender (the button which calls the function). As soon as it succeeds, we set it back. That's the simplest form of progress. Another approach is to show a piece of text somewhere on the page, but the most common way of doing it is to show a little piece of graphic which illustrates that the browser is currently working. You could make one yourself, or even better: Use one of the great online generators, for instance http://ajaxload.info/. I've created one, as you can see in the next example:



The process is pretty much the same, but instead of setting a text, we show and hide an existing image. You can place the image in a spot that the user is most likely to notice or dynamically place the image next to button/link clicked, if you have more than one. The possibilities are really endless. There is one problem with the above examples though: If the request fails for some reason, the progress is shown but never removed again. We can fix this by subscribing to the error event, where we can then remove the progress and then show an error message. Check out this example:


It's pretty much identical to the first example, but here we call the error function on the returned AJAX object and pass in a callback function which should be called if the request fails, which it will in this example, since I have changed the path for the requested file to something which doesn't exist.

Parent/child relation selectors

jQuery also allows you to select elements based on their parent element. There are two variations: One which will only match elements which are a direct child to the parent element, and one which will match all the way down through the hierarchy, e.g. a child of a child of a child of a parent element. The syntax for finding children which are direct descendants of an element looks like this:
$("div > a")
This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:
$("div a")
Here's an example where we color bold tags blue if they are directly descending from the first test area:
Bold text Italic text
Bold text 2 Italic text 2
Bold text 3
As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:
Bold text Italic text
Bold text 2 Italic text 2
Bold text 3
Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.

Using attributes

In the previous chapter, we saw how we could find elements in a page from their class or their ID. These two properties are related because of the fact that you can use them to style the elements with CSS, but with jQuery, you can actually find elements based on any kind of attribute. It comes with a bunch of attribute selector types and in this article, we will look into some of them. Find elements with a specific attribute The most basic task when selecting elements based on attributes is to find all the elements which has a specific attribute. Be aware that the next example doesn't require the attribute to have a specific value, in fact, it doesn't even require it to have a value. The syntax for this selector is a set of square brackets with the name of the desired attribute inside it, for instance [name] or [href]. Here is an example:
Test 1
Test 2
Test 3
We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value. Find elements with a specific value for a specific attribute Here's an example where we find elements with a specific value:

Link 1
Link 2
Link 3
The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy: $("a[target!='_blank']").append(" [same window]"); The difference is the != instead of =, a common way of negating an operator within many programming languages. And there's even more possibilities: Find elements with a value which starts with a specific string using the ^= operator:
$("input[name^='txt']").css("color", "blue");
Find elements with a value which ends with a specific string using the $= operator:
$("input[name$='letter']").css("color", "red");
Find elements with a value which contains a specific word:
$("input[name*='txt']").css("color", "blue");
 

Sample text

Sample Text

Sample Text