Doug Smith
Doug Smith

Reputation: 580

how to animate divs that are created dynamically?

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/

Upvotes: 1

Views: 93

Answers (2)

Sebastian G. Marinescu
Sebastian G. Marinescu

Reputation: 2394

You have an error when you give the generated DIVs a name:

var divName = "#floatName" + n;

change to

var divName = "floatName" + n;

The character # is not allowed in the ID attribute


Because right now your DIVs are generated like this:

<div id="#floatName0" class="randomFloat">Jimmy</div>

And to select this with jQuery you would need to write:

$("##floatName0")

Which throws an Sizzle-Error:

Uncaught Error: Syntax error, unrecognized expression: ##floatName0


See updated fiddle: https://jsfiddle.net/1fj32749/19/

Also see valid values for ID: What are valid values for the id attribute in HTML?

Upvotes: 2

AwokeKnowing
AwokeKnowing

Reputation: 8236

EDIT!!!: I found your error

change when dynamically creating the div (but not in the jquery part)

var divName = "#floatName" + n;

to

 var divName = "floatName" + n; //remove #

So the issue is that in pure javascript, you don't put a # to specify an id

final code:

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; // THIS WAS THE PROBLEM
        console.log(divName);
        var names = nameArray[n];
        var divTag = document.createElement('div');
        divTag.id = divName;           // BECAUSE HERE SHOULDN'T HAVE #
        divTag.innerHTML = names;
        divTag.style.position = "absolute";
        divTag.className = "randomFloat";
        document.body.appendChild(divTag);
  };

  $( document ).on('click', '#go', function() {
    var gotime = 1;
    interval = setInterval(function () {
      for(i = 0; i < 12; i++){
        
        $( "#floatName" + i ).animate({
        	left: Math.random()*500 + "px",
        	top: Math.random()*500 + "px"
        });
      };
      gotime += 1;
      if (gotime > 100) {
        clearInterval(interval);
      }
    }, 500) 
  });

  $( "#stop" ).click(function() {
        clearInterval(interval);
  });
.randomFloat {
    color: red;
    transition: 0.5s left, 0.5s top;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is this it?
<button id="go">&raquo; Run</button>
<button id="stop">&raquo; Stop</button>
<div id="randomFloat">Is it??</div>

Upvotes: 1

Related Questions