October 18, 2012

Load order of jquery animations

Question by Eric Baldwin

I am just starting a jQuery tutorial and I have a basic question on the load order of jQuery animations.

Clicking on a link causes both an alert and a hide animation to appear when I use the following HTML code:

 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
       $("a").click(function(event){
         alert("As you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
       $("a").click(function(event){
         event.preventDefault();
         $(this).hide("slow");
       });
     });
   </script>
 </body>

However, when I take the second click function out of the document.ready function so that the code looks as it does below, the popup appears and the text disappears, but the hide animation does not happen.

 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
   <style>
    a.test { font-weight: bold; }
  </style>
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
       $("a").click(function(event){
         alert("As you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
     });
     $("a").click(function(event){
       event.preventDefault();
       $(this).hide("slow");
     });
   </script>
 </body>
 </html>

Can anyone explain why the hide animation shows up only for the first example and not the second?

Answer by Starx

This is because the second handler is not get attached to all the anchor <a> tags on the div.

 $("a").click(function(event){ //This function will execute as the script loads
                               // and during this time, DOM might have been loaded yet
   event.preventDefault();
   $(this).hide("slow");
 });

But, by wrapping this inside.

$(document).ready(function() {

    // DOM is loaded

});

You first make sure the DOM is loaded first, then attach the handler.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!