I have animated a dynamic created element with setInterval. When the element is clicked I want it to change to a random direction (left, right, up or down).
I think the problem is that I can´t pass the randomly created direction into the setInterval function.
The html here....
<div id="klicker"></div>
The JavaScript here.....
var box = document.getElementById("klicker");
var x = 1;
var startp = 200;
box.onclick = function() {
var newdiv = document.createElement('div');
document.body.appendChild(newdiv);
newdiv.style.width = 200 + 'px';
newdiv.style.height = 200 + 'px';
newdiv.style.backgroundColor = 'grey';
newdiv.style.position = 'absolute';
newdiv.style.left = startp + "px";
newdiv.style.top = startp + "px";
newdiv.setAttribute('id', 'runner')
var run = document.getElementById('runner');
var dire = 'right';
run.onclick = function() {
var mov = function() {
randoms();
};
function randoms() {
alert('ddddd');
var rnd = (Math.random() * 4) + 1; //ranom number 1-4
var rnd_down = Math.floor(rnd); //make it en integer
/*--- make each number a uniqe direction---*/
if (rnd_down == 1) {
dire = 'right';
} else if (rnd_down == 2) {
dire = 'left';
} else if (rnd_down == 3) {
dire = 'up';
} else {
dire = 'down';
}
};
var moveit = setInterval(function() {
movefunc();
}, 50);
function movefunc() {
/*----each direction will make the div travel in diffrent directions--*/
if (dire = 'right') {
x = x + 1;
newdiv.style.left = x + 'px';
} else if (dire = 'left') {
x = x - 1;
newdiv.style.left = x + 'px';
} else if (dire = 'up') {
x = x - 1;
newdiv.style.top = x + 'px';
} else {
x = x + 1;
newdiv.style.top = x + 'px';
}
};
};
}
Aucun commentaire:
Enregistrer un commentaire