Chaining JQuery Show/Hide Using Callbacks

JQuery provides the capacity to do animated showing and hiding of elements through the show(speed, callback) and hide(speed, callback) functions. As you can see, these two functions take an optional speed parameter, and an optional callback. Speed specifies how slowly the animation is performed, while callback specifies a function to call when the animation is done. Below, we will use the callback to chain animations together.

Here’s the example

Here’s the code.. the nested callbacks get a little hairy, but it’s functional and devoid of confusing abstraction.

<script type="text/javascript">
  $ =  jQuery.noConflict();
  var speed = 500;
  $(function() {
    $("#hide").hide();
    $(".blueBox").hide();
    $("#show").click(function() {
       $(this).hide();
       $("#1").show(speed, function() {
         $("#2").show(speed, function() {
           $("#3").show(speed, function() {
             $("#4").show(speed, function() {
               $("#5").show(speed,function() {
                 $("#6").show(speed, function() {
                   $("#hide").show();
                 })
               })
             })
           }) 
         })
       })
    });
 
 
    $("#hide").click(function() {
      $(this).hide();
        $("#6").hide(speed, function() {
          $("#5").hide(speed, function() {
            $("#4").hide(speed, function() {
              $("#3").hide(speed, function() {
                $("#2").hide(speed,function() {
                  $("#1").hide(speed, function() {
                    $("#show").show();
                  })
               })
             })
           }) 
         })
        })
      });
   });        
</script>
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. 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=""> <strike> <strong> <pre lang="" line="" escaped="">