dimanche 28 juin 2015

Changing an appended clone object in a loop - Javascript

I have a working JavaScript gist that create randomly three squares on the screen. The problem is now it's creating via the toAppend and clone() (see Initial Code at the bottom) 3 times the very same html block.

It generates currently:

<div class="info-square"><span class="square" data-target="#myInfoModal" data-toggle="modal" ></span></div>
<div class="info-square"><span class="square" data-target="#myInfoModal" data-toggle="modal" ></span></div>
<div class="info-square"><span class="square" data-target="#myInfoModal" data-toggle="modal" ></span></div>

I would like to have TO generate for each a different data-target for each div, like that:

<div class="info-square"><span class="square" data-target="#myInfoModal1"  data-toggle="modal" ></span></div>
<div class="info-square"><span class="square" data-target="#myInfoModal2"  data-toggle="modal" ></span></div>
<div class="info-square"><span class="square" data-target="#myInfoModal3"  data-toggle="modal" ></span></div>

The number 3 would come from the "var numInfoSquares"

INITIAL CODE

$(document).on('ready page:load', function () { 

    // Use jquery to display X squares according 
    var numInfoSquares = 3;
    var $zone = $("#zone");
    var $toAppend = $('<div class="info-square"><span class="square" data-toggle="modal" data-target="#myInfoModal"></span></div>');
    for (var c = 0; c < numInfoSquares; c++)
      $zone.append($toAppend.clone());
    // place squares randomly on the page
    function getRandomInt(min, max) {
      return Math.random() * (max - min + 1) + min;
    }
    $(".info-square").each(function () {
      var topPosition = getRandomInt(8, 70);  
      var leftPosition = getRandomInt(8, 92); 
      $(this).css({
        "top": topPosition+"%",
        "left": leftPosition+"%",
      });
    });   
  });  

Aucun commentaire:

Enregistrer un commentaire