March 31, 2012

jQuery sliding animation not working

Question by Jake Zeitz

I have three divs stacked on each other but offset so that a part of each div is visible. When one of the bottom divs is clicked I want the top div to animate out and back into the stack at the bottom, then the div that is clicked will appear at the top. So far I only have the code for when the middle div is clicked, but I cannot get it to work properly. What am I doing wrong? (I also realize that the code I wrote is probably terrible, this is the first jQuery code I have written.)

The css is very very simple:

    .first {
        z-index: 3;
    }
    .second {
        z-index: 2;
    }
    .third {
        z-index: 1;
    }

The basic html is this:

    <div class="first"></div>
    <div class="second"></div>
    <div class="third"></div>

Here is my code:

    $("div.second").click(function () {
        $("div.first").animate({
            left: "-=200px"},
            {duration: "fast",
            complete: function () {
                $("div.first").removeClass("first").addClass("third").animate({left: "+=350px", top: "+=60px"}, "fast");
            }
        });
        $("div.second").animate({
            left: "-=24px", top: "-=30px"},
            {duration: "fast",
            complete: function () {
                $("div.second").removeClass("second").addClass("first");
            }
        });
        $("div.third").animate({
            left: "-=24px", top: "-=30px"},
            {duration: "fast",
            complete: function () {
                $("div.third").removeClass("third").addClass("second");
            }
        });
    });

I can get the div.first to move to the side and back. But now I can’t get the classes to stay changed. What keeps happening is the div.second will remove it’s class and add .first in the animation, but when the animation is complete, it acts like it still has a class of .second.

Answer by Starx

That coding style is very inefficient.

Use something like this, It applies to every div

$("div").click(function() {
   var first = $(".first");
   var fleft = first.css("left");
   var ftop = first.css("top");           

   var $this = $(this);
   var tLeft = $this.css('left');
   var tTop = $this.css('top');
   var tClass = $this.attr("class");

   first.animate({
      left: tLeft,
      top: tTop
   }).attr("class", tClass);

   $this.animate({
       top: ftop,
       left: fleft
   }).attr("class", "first");        

});

Demo

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!