Shahjalal
Shahjalal

Reputation: 1151

Animate an image from one div to another

I have two div tag in my code. one div contains an image of 200 x 200 dimension. The other div does not contain anything. I want to animate this 200 x 200 image to my empty div of 30 x 30 image. I wrote the code, but it does not work. Even, it does not show any error in firebug. Could anyone please help me??

HTML

<div>
    <img class="userimage" src="images/TF-NKWS-003.png" height="200" width="200" />
</div>

<input type="button" value="Click me to amimate" class="animationButton" />
<br><br><br><br><br><br><br><br>

<div class="addImg">
</div>

Javascript

<script type="text/javascript">

    $(".animationButton").click(function(){
        $(this).find(".userimage").animate({
        left:$(".addImg").offset().left,
        top:$(".addImg").offset().top,
        width:30,
        height:30
        }, 1000, function(){
                 $(".addImg").append("<img src='images/TF-NKWS-003.png' />");
                 });
    });

</script>

Thanks in advance

Upvotes: 1

Views: 1560

Answers (2)

Daniele
Daniele

Reputation: 1938

You can find a jsFiddle using fixed code:

$(".animationButton").click(function(){
        $(".userimage").animate({
            left:$(".addImg").offset().left,
            top:$(".addImg").offset().top,
            width:30,
            height:30
          },1000,function(){
            $(".addImg").append("<img src='http://placehold.it/80x80&text=image1' />");
        });
    });

Upvotes: 1

putvande
putvande

Reputation: 15213

That is because your selector is wrong. Your image is not inside the button. Try it like this:

<script type="text/javascript">

    $(".animationButton").click(function(){

        $(".userimage").animate({
            left:$(".addImg").offset().left,
            top:$(".addImg").offset().top,
            width:30,
            height:30
          },1000,function(){
            $(".addImg").append("<img src='images/TF-NKWS-003.png' />");
        });
    });

</script>

Your selector $(this).find('.userimage') was looking for the userimage inside the $(this) (.animationButton).

Your script also makes a copy of the image, I don't know if that is what you want, if not you should replace $(".addImg").append("<img src='images/TF-NKWS-003.png' />"); with $(this).appendTo(".addImg");. That appends the original image to the div.

Upvotes: 1

Related Questions