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.
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.
Share Improve this question edited Jul 21, 2011 at 12:12 dilbert asked Jul 21, 2011 at 12:10 dilbertdilbert 1271 silver badge8 bronze badges 04 Answers
Reset to default 7If 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/dkuVu/
Use jQuery for creation of elements, and animate it when appending:
function drawSpot() {
var myH1 = $("<div>").css({ position: "absolute",
top: GetRandom(0,100)+"%",
left: GetRandom(0,100)+"%",
width: 40,
height: 40 });
$("body").append(myH1.animate(...));
}
http://jsfiddle/nagCf/
That should work
function drawSpot()
{
var myH1 = '<div id="newDiv">Some Text</div>';
$("body").append(myH1);
$("#newDiv").css({'position' : 'absolute',
'top' : GetRandom(0,100)+"%",
'left' :GetRandom(0,100)+"%",
'width':'40px',
'height':'40px'
});
$("#newDiv").hide().fadeIn(500);
}
You can use : $(myH1).animate({left:'*randomvalue*', top:'*randomvalue*'},1000);
after the append
.
http://jsfiddle/Wumrr/2/