Reputation: 175
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
Reputation: 288130
Some points:
this
value.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
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