Week 9: DEMO

jQuery Chaining



Many of jQuerys methods can be chained together into sequences that will play out in the order you determine. Each step in the sequence will play out over the duration provided (or the default duration, usually one second) before the next method in the chain begins. The box below will fade out over 2 seconds, wait another 2 seconds, then fade back in over half a second.

Click here to activate a sequence.

$("#chain1").click(function(){
    $(this).fadeOut(2000).delay(2000).fadeIn(500);
});

Notice that after fadeOut() has been performed, the rest of the page moves up to fill in that space, as jQuery has set the display property of that element to none. As part of the chain, we can modify different components of the HTML, whether it be the content, the CSS, or the attributes that it uses. Below is an example of trying to fade out an element, change its CSS, and then fade it back in...

Click here to activate a sequence.

$("#chain2").click(function(){
    $(this).fadeOut(2000).css("background-color", "red").fadeIn(500);
});

Wait a minute, that's not what we expected to happen. Instead of it fading out and then changing the background color, the background color changes immediately and then it fades out. This is maybe counter-intuitive, but in jQuery some of the methods will not wait for the previous chain method to execute to completion before it gets executed. If we want to ensure that the CSS changes at exactly the time we would like, we need to incorporate a callback function into one of the methods to be specific that the code should execute at the end of that method.

Click here to activate a sequence.

$("#chain3").click(function(){
    $(this).fadeOut(2000, function(){
        $(this).css("background-color", "red");
    }).fadeIn(500);
});

Not only can we change the CSS of elements, but we can swap out attributes. What if we want to fade out, then switch out the URL for the image element below, then fade it back in?



$("#chain4").click(function(){
    $(this).fadeOut(2000, function(){
        $(this).attr("src", "../week2/tacos9.jpg");
    }).fadeIn(500);
});

There are a number of great jQuery methods for animating the visual appearance of the HTML element, but we can customize the type of animation we would like to achieve using the animate() method. The power behind this method is that it can animate any number of properties simultaneously over a specified period of time. More details on this when we get to week 13.

Click here to animate some CSS properties.

$("#chain5").click(function(){
    $(this).animate({
        width: "95%",
        height: "300px",
        opacity: 0.5
    }, 2000);
});

Resources