jQuery : Stopping animations with the stop() method

In the previous chapter, we saw how we could do custom animations using the animate() method and how we could have several animations after each other, by making several animation calls and thereby using the animation queue of jQuery. However, sometimes you need to stop an animation before it finishes, and for this, jQuery has the stop() method. It works for all effects related jQuery functions, including sliding, fading and custom animations with the animate() method. Here's an example where we use it:

<a href="javascript:void(0);" onclick="$('#divTestArea1').slideDown(5000);">Show box</a>   <a href="javascript:void(0);" onclick="$('#divTestArea1').stop();">Stop</a><div id="divTestArea1" style="padding: 100px; background-color: #89BC38; text-align: center; display: none;">        <b>Hello, world!</b></div>
To make the example a bit more compact, I have used inline calls in the onclick events of the two links. When you click the first link, the slideDown() method is used on our div element, starting a slow slide down. A click on the second link will kill the current animation being performed on the selected element. This is the default behavior of the stop() method, but two optional parameters allows us to do things differently. The first parameter specifies whether the animation queue should be cleared or not. The default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The following example will demonstrate that:

<a href="javascript:void(0);" onclick="$('#divTestArea2').slideDown(5000).slideUp(5000);">Show box</a>   <a href="javascript:void(0);" onclick="$('#divTestArea2').stop();">Stop</a>   <a href="javascript:void(0);" onclick="$('#divTestArea2').stop(true);">Stop all</a>   <a href="javascript:void(0);" onclick="$('#divTestArea2').clearQueue().hide();">Reset</a><div id="divTestArea2" style="padding: 100px; background-color: #89BC38; text-align: center; display: none;">        <b>Hello, world!</b></div>
We have added a second animation to the "Show box" link. This will slowly slide down the box, and once done, slide it up again. The queue system makes sure that these steps are performed in sequence. Now, click the "Reset" link to have the box hidden again and then click the "Show box" link once more, followed by a click on "Stop". You will see that the first animation is stopped, allowing for the second animation to be executed. However, if you try again and click on the "Stop all" instead, the true value passed will make sure that the entire queue is cleared and that all animation on the element is stopped.

The second parameter tells jQuery whether you would like for it to just stop where it is, or rush through the animation instead, allowing for it to finish. This makes a pretty big difference, because as you can see from the first example, once you hit stop, the default behavior is to simply stop the animation where it is and leave it like that. The following example will show you the difference:

<a href="javascript:void(0);" onclick="$('#divTestArea3').slideDown(5000);">Show box</a>   <a href="javascript:void(0);" onclick="$('#divTestArea3').stop(true);">Stop</a>   <a href="javascript:void(0);" onclick="$('#divTestArea3').stop(true, true);">Stop but finish</a>   <a href="javascript:void(0);" onclick="$('#divTestArea3').clearQueue().hide();">Reset</a><div id="divTestArea3" style="padding: 100px; background-color: #89BC38; text-align: center; display: none;">        <b>Hello, world!</b></div>
Try the two "Stop" variations - the first will stop immediately, while the second one will rush the animation to finish.











jQuery : Custom animations with the animate() method

In previous chapters, we looked into the built-in fading and sliding effect methods of jQuery. However, you can much more than just that. With the animate() method, you can create custom animations where you manipulate pretty much any numerical CSS property of an element. This allows you to e.g. move a box slowly across the screen or have it jump up and down. Let's try something very simple:

<div style="height: 60px;">        <div id="divTestBox1" style="height: 50px; width: 50px; background-color: #89BC38; position: absolute;"></div></div><script type="text/javascript">
$(function(){        $("#divTestBox1").animate(                {                        "left" : "200px"                }        );});</script>
The first, and only required, parameter of the animate function is a map of the CSS properties that you wish to have altered. In this case, we have an absolutely positioned div element, which we tell jQuery to move until it has reached a left property of 200 pixels.
The second parameter allows you to specify the duration of the animation in milliseconds or as "slow" or "fast" which is the same as 600 or 200 ms. With this, we can slow down the above example as much as we want:

<div style="height: 60px;">        <div id="divTestBox2" style="height: 50px; width: 50px; background-color: #89BC38; position: absolute;"></div></div><script type="text/javascript">
$(function(){        $("#divTestBox2").animate(                {                        "left" : "200px"                }, 
                5000        );});</script>
As the third parameter, we can specify a callback function to be called once the animation is done. This can be very useful for performing a number of different animations in a row. For instance, check out this example:

<div style="height: 40px;">        <div id="divTestBox3" style="height: 20px; width: 20px; background-color: #89BC38; position: absolute;"></div></div><script type="text/javascript">
$(function(){        $("#divTestBox3").animate(                { "left" : "100px" }, 
                1000,                function()                {                        $(this).animate(                                { "left" : "20px" },                                500,                                function()                                {                                        $(this).animate({ "left" : "50px" }, 500);                                }                        )                }        );});</script>
It might seem a bit overwhelming, but what we do is that we call the animate method and ask for the left property of our test "div" to be animated until it reaches a left of 100 pixels. We want it to take 1 second (1000 milliseconds) and once it completes, we wish for a new animation to start, which moves it back to 20 pixels within half a second, and as soon as THAT animation is done, we move it a bit right again, so that it now has a left property of 50 pixels.

However, since jQuery comes with queue functionality for animations, you can actually achieve the above example in a much simpler manner. This however only applies when you want a set of animations to performed after each other - if you want to do something else when an animation is complete, the above example will still be the way to go. Here's the queue version:

<div style="height: 40px;">        <div id="divTestBox4" style="height: 20px; width: 20px; background-color: #89BC38; position: absolute;"></div></div><script type="text/javascript">
$(function(){        $("#divTestBox4").animate({ "left" : "100px" }, 1000);        $("#divTestBox4").animate({ "left" : "20px" }, 500);        $("#divTestBox4").animate({ "left" : "50px" }, 500);});</script>















jQuery : 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:

<div id="divTestArea1" style="padding: 50px; background-color: #89BC38; text-align: center; display: none;">        <b>Hello, world!</b></div><a href="javascript:void(0);" onclick="ShowBox();">Show box</a><script type="text/javascript">function ShowBox(){        $("#divTestArea1").slideDown();}</script>
For hiding the box again, we can use the slideUp() method. They both take the same set of parameters, which are all optional. The first parameter allows you to specify a duration for the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds.Let's try an example where we do just that:

<div id="divTestArea21" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><div id="divTestArea22" style="width: 50px; height: 50px; display: none; background-color: #C3D1DF;"></div><div id="divTestArea23" style="width: 50px; height: 50px; display: none; background-color: #9966FF;"></div><a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a><script type="text/javascript">function ShowBoxes(){        $("#divTestArea21").slideDown("fast");        $("#divTestArea22").slideDown("slow");        $("#divTestArea23").slideDown(2000);}</script>
There's a bit more HTML than usual, but that's only there for you to be able to see the different paces in which the boxes are shown. Notice how the first box is there almost instantly, the second box is pretty close and the third box is slower, because it uses a full two seconds to slide down.

Now, the second parameter can either be the name of an easing function (which we won't use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here's an example of that, combined with the use of the slideUp() method:
<div id="divTestArea3" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><script type="text/javascript">
$(function(){        $("#divTestArea3").slideDown(2000, function()        {                $("#divTestArea3").slideUp(3000);        });});</script>
The ability to do this can be very useful for combining several effects, as you can see. In this example, the callback function we supply will be called as soon as the slideDown() method is completely finished and then the slideUp() method is called.

In case you want to simply slide an element up or down depending on its current state, the jQuery developers have provided us with a nice slideToggle() method for doing just that. Check out the next example, where we use it:

<div id="divTestArea4" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><br /><a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a><script type="text/javascript">function ToggleBox(){        $("#divTestArea4").slideToggle("slow"); }</script>

















jQuery : 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:

<div id="divTestArea1" style="padding: 50px; background-color: #89BC38; text-align: center; display: none;">        <b>Hello, world!</b></div><a href="javascript:void(0);" onclick="ShowBox();">Show box</a><script type="text/javascript">function ShowBox(){        $("#divTestArea1").fadeIn();}</script>
You can fade a lot of different elements, like divs, spans or links. The fadeIn() method can take up to three parameters. The first one allows you to specify the duration of the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds. Here's an example of it in use:

<div id="divTestArea21" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><div id="divTestArea22" style="width: 50px; height: 50px; display: none; background-color: #C3D1DF;"></div><div id="divTestArea23" style="width: 50px; height: 50px; display: none; background-color: #9966FF;"></div><a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a><script type="text/javascript">function ShowBoxes(){        $("#divTestArea21").fadeIn("fast");        $("#divTestArea22").fadeIn("slow");        $("#divTestArea23").fadeIn(2000);}</script>
Don't mind all the HTML, it's just there so that you can see the difference between the fading durations. Now, the second parameter can either be the name of an easing function (which we won't use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here's an example of that, combined with the use of the fadeOut() method, which obviously has the reverse effect of fadeIn():

<div id="divTestArea3" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><script type="text/javascript">
$(function(){        $("#divTestArea3").fadeIn(2000, function()        {                $("#divTestArea3").fadeOut(3000);        });});</script>
There may be situations where you want to fade an element in our out depending on its current state. You could of course check if it is visible or not and then call either fadeIn() or fadeOut(), but the nice jQuery developers have supplied us with a specific method for toggling an element, called fadeToggle(). It takes the same parameters as fadeIn() and fadeOut(), so it's very easy to use. Here's a little example:

<div id="divTestArea4" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><br /><a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a><script type="text/javascript">function ToggleBox(){        $("#divTestArea4").fadeToggle("slow");  }</script>
And that's how easy it is to use the fading effects of jQuery.












jQuery : 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:

<div id="divTestArea1">        <b>Bold text</b>        <i>Italic text</i>        <div id="divTestArea2">                <b>Bold text 2</b>                <i>Italic text 2</i>                <div>                        <b>Bold text 3</b>                </div>        </div></div><script type="text/javascript">
$("#divTestArea1 > b").css("color", "blue");</script>
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:

<div id="divTestArea1">        <b>Bold text</b>        <i>Italic text</i>        <div id="divTestArea2">                <b>Bold text 2</b>                <i>Italic text 2</i>                <div>                        <b>Bold text 3</b>                </div>        </div></div><script type="text/javascript">
$("#divTestArea1 b").css("color", "blue");</script>
Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method.









jQuery : Using Attributes

In 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:

<span title="Title 1">Test 1</span><br /><span>Test 2</span><br /><span title="Title 3">Test 3</span><br /><script type="text/javascript">
$(function(){        $("[title]").css("text-decoration", "underline");});</script>
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:
<a href="http://www.google.com" target="_blank">Link 1</a><br /><a href="http://www.google.com" target="_self">Link 2</a><br /><a href="http://www.google.com" target="_blank">Link 3</a><br /><script type="text/javascript">
$(function(){        $("a[target='_blank']").append(" [new window]");});</script>
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");