I'm trying to create a square that will appear in a random place within a 300x300px space. It is currently moving horizontally but not vertically. Can someone help me get it to move vertically as well? Thank you!
#square {width: 200px;
height: 200px;
display: none;
position: relative;
}
var top=Math.random();
top=top*300;
var left=Math.random();
left=left*300;
document.getElementById("square").style.top=top+"px";
document.getElementById("square").style.left=left+"px";
I'm trying to create a square that will appear in a random place within a 300x300px space. It is currently moving horizontally but not vertically. Can someone help me get it to move vertically as well? Thank you!
#square {width: 200px;
height: 200px;
display: none;
position: relative;
}
var top=Math.random();
top=top*300;
var left=Math.random();
left=left*300;
document.getElementById("square").style.top=top+"px";
document.getElementById("square").style.left=left+"px";
Share
Improve this question
asked Mar 12, 2017 at 21:13
Denise WalterDenise Walter
1231 gold badge4 silver badges6 bronze badges
1
- 1 Works for me: jsfiddle/f3chy9mk The problem is somewhere else. You'll have to show an example that replicates the problem. – JJJ Commented Mar 12, 2017 at 21:20
2 Answers
Reset to default 2Use left
to translate horizontally and top
for vertically.
const getRandom = (min, max) => Math.floor(Math.random()*(max-min+1)+min);
const square= document.querySelector('#square');
setInterval(() => {
square.style.left= getRandom(0, 300 - 200)+'px'; //