简体   繁体   中英

How to animate cloned element in jQuery

Today I've been trying to write function which would clone an element, and then animate the clone, then delete previous one and loop it.

There is a badge with number on in, which counts how many times animation went off. I wanted to animate that badge, so it would scale 2x, get the next number and go to the normal size.

Right now I'm trying to only animate the badge and then combine everything together. I came up with that code:

function badgeClone() {

var badge1 = $('.badge');
var badge2 = $('.badge').clone();

var badgeWidth = badge1.width();
var badgeHeight = badge1.height();

    badge1.after(badge2);

    badge2.animate({
        'width': badgeWidth * 2 + 'px',
        'height': badgeHeight *2 + 'px'},
        500);

}

But to be honest, it does exactly nothing after calling that function in document.ready, there is no animation. I assume I do something wrong, but logically, it should work.

I'd appreciate any help from you guys, cheers!

EDIT:

I added that counter to that function but I wonder why it does not return initial 0, it starts showing from "1".

var count = 0;

function badgeClone() {

var badge1 = $('.badge');
var badge2 = $('.badge').clone();

var badgeWidth = badge1.width();
var badgeHeight = badge1.height();

    badge1.text(count);

    badge1.after(badge2);

    badge2.animate({
        'width': badgeWidth * 2 + 'px',
        'height': badgeHeight *2 + 'px'},
        200, function() {

            count++
            badge2.text(count);

            badge2.delay(200).animate({
                'width': badgeWidth + 'px',
                'height': badgeHeight + 'px'},
                200);
            badge1.remove(); 
        });          
 }

That function is called later in other function, I'll try to make a similar fiddle with entire idea if necessary.

Cheers!

Your code is okay. Im not sure how you call badgeClone(), but for me it works. Have a look at this fiddle: http://jsfiddle.net/

Please also look up the possible error in your console https://developers.google.com/chrome-developer-tools/docs/javascript-debugging?hl=de .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM