Search code examples
jqueryhtmlcloneexponential

jquery clone, exponential <div> creation


Im currently creating an application in which user's are able to drag items to a mailbox.

After they drop the item, a new image is created "behind" the mailbox, giving you the feeling it is actually falling in.

Im using the following code to create and animate new images everytime a person drops an item:

function animateDrop(){
animateArray.push($('.animateDrop').clone())
xArray.push(xPos)
yArray.push(yPos)

var foo = animateArray[animateArray.length - 1];
var finalxPos = xArray[xArray.length - 1];
var finalyPos = yArray[yArray.length - 1];

$('body').append(foo);
foo.css({'left': finalxPos, 'top': finalyPos + 40}).fadeIn('slow');
foo.animate({'top': '+=100px'},1500);
};
animateDrop();

When the code is executed the a new image is created, but dropping more items is causing an exponential growth in div's that are being created.

Somewhere its remembering all of the previously created divs and appends all of them again to the body (atleast that is what is looks like to me).

I am currently stuck on a way to prevent this, any help would be appreciated.

UPDATE 24-10-2011: animateArray.push($('.animateDrop').first().clone()) Adding the .first() to the array push solved the problem of creating multiple divs.


Solution

  • Just use jQuery's first() or :first selector before the cloning call. That should do the trick.