Im trying to make an image move to a random spot on the webpage after 5 seconds so far I have this:
var image = document.getElementById('image');
var position = 0;
var timing = setInterval(timing, 5000);
image.style.position = 'relative';
image.onclick=function move(direction){
var top = Math.floor(Math.random()*75);
var left = Math.floor(Math.random()*75);
var right = Math.floor(Math.random()*75);
var bottom = Math.floor(Math.random()*75);
image.style.top = top + 'px';
image.style.left = left + 'px';
image.style.right = right + 'px';
image.style.bottom = bottom + 'px';
}
How do I get it to move after 5 seconds?
Advertisement
Answer
- create an moveImage function:
function moveImage(){
var top = Math.floor(Math.random()*75);
var left = Math.floor(Math.random()*75);
var right = Math.floor(Math.random()*75);
var bottom = Math.floor(Math.random()*75);
image.style.top = top + 'px';
image.style.left = left + 'px';
image.style.right = right + 'px';
image.style.bottom = bottom + 'px';
}
- Update the onClick to use the new function:
image.addEventListener('click', moveImage);
- Update the interval to use the new function:
var timing = setInterval(moveImage, 5000);
The whole thing:
var image = document.getElementById('image');
image.style.position = 'relative';
function moveImage(){
var top = Math.floor(Math.random()*75);
var left = Math.floor(Math.random()*75);
var right = Math.floor(Math.random()*75);
var bottom = Math.floor(Math.random()*75);
image.style.top = top + 'px';
image.style.left = left + 'px';
image.style.right = right + 'px';
image.style.bottom = bottom + 'px';
};
image.addEventListener('click', moveImage);
var timing = setInterval(moveImage, 5000);