Lulu
Lulu

Reputation: 175

Move a button created dynamically JavaScript

I am a very beginner! I've dynamically created a random number of buttons. After creation, I want them to automatically start moving. From some reason or another, my code creates the buttons, but doesn't make them move.

javascript.js

function myFunction() {
    for (i = 1; i<=Math.random() * 10; i++){
            var x = document.createElement("button");
            x.id = i;
            x.innerHTML = i;
            
            document.body.appendChild(x);
            moveMe(x.id);
            var v1 = Math.floor(Math.random() * 255);
            var v2 = Math.floor(Math.random() * 255);
            var v3 = Math.floor(Math.random() * 255);
            x.style.backgroundColor = "rgb(" + v1 + "," + v2 + "," + v3 + ")";
        
        }
}

function uMM(id){
    var x = document.getElementById(id);
    x.pozx = x.pozx + 1;
    x.pozy = x.pozy + 1;
    x.style.left = x.pozx + "px";
    x.style.top = x.pozy + "px";

}
function moveMe(id){
    var x = document.getElementById(id);
    x.pozx = 0;
    x.pozy = 0;
    setInterval( "uMM(" + id + ")", 1000);
}

home.php

<input type="text" id="demo">

Upvotes: 0

Views: 150

Answers (2)

Oriol
Oriol

Reputation: 288130

Some points:

  • Loop conditions are evaluated at each iteration. Therefore, you were comparing each time against a new random number, so the probability of the number of buttons wasn't uniform.
  • You don't need IDs. Just pass a reference to the element as an argument or as the this value.
  • Don't use setTimeout nor setInterval with strings, because it's like evil eval! Instead, use functions.

(function myFunction() {
  for (var i=1, l=Math.random()*10; i<=l; ++i){
    var x = document.createElement("button");
    x.innerHTML = i;
    document.body.appendChild(x);
    moveMe(x);
    var rgb = Array.apply(null, Array(3)).map(function() {
      return Math.floor(Math.random() * 255);
    }).join(',');
    x.style.backgroundColor = "rgb(" + rgb + ")";
  }
})();
function uMM(){
  var x = this;
  x.style.left = ++x.pozx + "px";
  x.style.top = ++x.pozy + "px";
}
function moveMe(x){
  x.pozx = x.pozy = 0;
  setInterval(uMM.bind(x), 1e3);
}
button {
  position: relative;
}

Upvotes: 3

Jan
Jan

Reputation: 2853

Your element-ID must begin with a letter ([A-Za-z]).

var x = document.createElement("button");
x.id = 'dyn-button-' + i;

Upvotes: 0

Related Questions