tags:

views:

127

answers:

1

Hey guys, I have written this code from the ground up using jQuery (first real jQuery project), and so far, I have some toggle animation. My code looks like this:

HTML

<div id="content">   
    <div class="featured-img one">
     <img src="media/desktopography.png" alt="Desktopography"/>
    </div><!-- end .featured-img -->

    <div class="featured-img two">
     <img src="media/dancer.png" alt="Dancer"/>
    </div><!-- end .featured-img -->

    <div class="featured-img three">
     <img src="media/tech.png" alt="Tech"/>
    </div><!-- end .featured-img -->

    <div class="featured-img four">
     <img src="media/strawberry-tree.png" alt="Strawberry Tree"/>
    </div><!-- end .featured-img -->

    <div class="featured-img five">
     <img src="media/snow-leopard.png" alt="Snow Leopard"/>
    </div><!-- end .featured-img -->
</div><!-- end #content -->

jQuery

$(document).ready(function(){
  $('.featured-img').toggle(
  function() {
   $(this).animate({ 
          height: "600px",
          marginTop: "-100px"
 }, 500 );
        $(".featured-img > img").animate({ 
          marginTop: "0px"
 }, 500 );
  },
  function() {
   $(this).animate({ 
          height: "150px",
          marginTop: "100px"
 }, 1500 );
        $(".featured-img > img").animate({ 
          marginTop: "-200px"
 }, 1500 );
  }
   );
 });

This works fine with one element, BUT it applies the same animation to every element assigned .featured-img on each click. Is there any way I can only animate the element I clicked, without disturbing the other ones at all?

I have tried playing with :not(:animated), and other stuff, but it only made it worse. I would appreciate any help or suggestions.

Thanks in advance!

A: 

Hey everyone, after doing some more research, I figured it out. I knew from the beginning that the reason the other objects were animated because the classes were shared throughout. The way to avoid that is to target only the child of the element we clicked using the jQuery child selector $(this).children(). You can see the functional demo here. My code looks like this:

$(document).ready(function(){
    $('.featured-img').toggle(
     function() {
      $(this).animate({ 
             height: "593px",
             marginTop: "-100px"
      }, 500 );
         $(this).children().animate({ 
             marginTop: "0px"
      }, 500 );
     },
     function() {
      $(this).animate({ 
             height: "150px",
             marginTop: "100px"
      }, 1500 );
         $(this).children().animate({ 
             marginTop: "-200px"
      }, 1500 );
     }
      );
    });

I hope you guys have learned something new. Thanks for all those who helped.

Michal Kopanski