I've been able to animate divs using jquery, and I've been able to dynamically create divs. However, I'm problems animating the divs after they are dynamically created.
The code below dynamically creates div ok:
var nameArray = [
"Jimmy",
"Sonny",
"Sammy",
"Henry",
"Hank",
"Susan",
"Sebby",
"Alyssa",
"Pepper",
"Ken",
"Steve",
"Kandi",
"Wes"
];
var numberStudents = nameArray.length;
var interval;
for(n = 0; n < numberStudents; n++){
var divName = "#floatName" + n;
console.log(divName);
var names = nameArray[n];
var divTag = document.createElement('div');
divTag.id = divName;
divTag.innerHTML = names;
divTag.style.position = "absolute";
divTag.className = "randomFloat";
document.body.appendChild(divTag);
};
The following animation works if I type in the divs manually:
var loopAllowed = false;
$( "#go" ).click(function() {
loopAllowed = true;
var max = 12;
var loop = function(){
for(i = 0; i < 12; i++){
var divName = "floatName" + i;
console.log(divName);
$( "#" + divName ).animate({
left: Math.random()*500 + "px",
top: Math.random()*500 + "px"
}, 500, i == max - 1 && loopAllowed ? loop : undefined);
}
};
loop();
});
$( "#stop" ).click(function() {
loopAllowed = false;
});
I think the problem may have to do with having to delegate an event. One idea is to use
$( "#randomFloat" ).on("click", "#go", function() {
I got this idea from reading this here: jQuery - selecting dynamically created divs
It doesn't work in my case though.
JSFiddle for the dynamically created divs that I'm having problems with: https://jsfiddle.net/shmish/1fj32749/17/
JSFiddle for manually creating divs and animating them: https://jsfiddle.net/shmish/3s5vn2yL/2/