Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

animate element dynamically on creation

I want to dynamically create divs, append them to the body and set a jQuery animation.

This is where the elements are created:

function drawSpot()
{
 var myH1 = document.createElement("div");
 myH1.style.position = "absolute";
 myH1.style.top = GetRandom(0,100)+"%";
 myH1.style.left = GetRandom(0,100)+"%";
 myH1.style.width="40px";
 myH1.style.height="40px";
 $("body").append(myH1);

}

And from the time on they are appended to the body, I want to start the animation.

like image 477
dilbert Avatar asked Jul 15 '26 08:07

dilbert


1 Answers

If you already using jQuery, you should do it all the way:

$('<div>', {
    css: {
        position:   'absolute',
        top:        GetRandom(0,100)+'%',
        left:       GetRandom(0,100)+'%',
        width:      '40px',
        height:     '40px'
    }
}).appendTo( document.body ).animate({
    left:  '100%'  // for instance
}, 2000);

By using .appendTo() you still have a reference to your original object and be able to chain methods on it.

Ref.: jQuery constructor, .appendTo(), .animate()

demo: http://jsfiddle.net/dkuVu/

like image 127
jAndy Avatar answered Jul 18 '26 23:07

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!