Reputation: 3
I am trying to add two classes to a div tag. I am using variables with randomized values to calculate the position of the div tags. I don't know how to create a class with these randomized numbers, if it is even possible, could someone help me out?
I don't really know where to start but here's my code
let xValues = []
let yValues = []
let coordinates = []
for (let i = 0; i < 10; i++) {
xValues.push(i)
yValues.push(i)
}
let x1 = xValues[Math.floor(Math.random()*xValues.length)]
let x2 = xValues[Math.floor(Math.random()*xValues.length)]
let x3 = xValues[Math.floor(Math.random()*xValues.length)]
x1 = x1 * 50
x2 = x2 * 50
x3 = x3 * 50
let y1 = yValues[Math.floor(Math.random()*yValues.length)]
let y2 = yValues[Math.floor(Math.random()*yValues.length)]
let y3 = yValues[Math.floor(Math.random()*yValues.length)]
y1 = y1 * 50
y2 = y2 * 50
y3 = y3 * 50
console.log("("+x1+", "+y1+") "+"("+x2+", "+y2+") "+"("+x3+", "+y3+")")
html, body {
height: 100%;
width: 100%;
background-color: grey;
}
.bg{
height: 500px;
width: 500px;
background-color: white;
position: relative
}
.obst {
background-color: red;
height: 50px;
width: 50px;
display: inline-block;
}
#obst1 {
position: absolute;
top: 300px;
left: 450px;
}
#obst2 {
position: absolute;
top: 200px;
left: 200px;
}
#obst3 {
position: absolute;
top: 100px;
left: 300px;
}
<body>
<div class="bg">
<div class="obst" id="obst1"></div>
<div class="obst" id="obst2"></div>
<div class="obst" id="obst3"></div>
</div>
<button onclick="play()"
<script src="script.js"></script>
</body>
I'm very new to coding as well as stack overflow so if I mess something up I am sorry.
Upvotes: 0
Views: 57
Reputation: 28226
Here is another - shorter - way of doing it:
function rnd(n){
return Math.floor(Math.random() * n);
}
document.querySelectorAll(".obst").forEach(o=>{
o.style.top=rnd(200)+"px";
o.style.left=rnd(200)+"px";
});
.obst{ padding: 6px;
background-color:#fff;
border: 1px solid #888;
position: absolute; }
<div>
<div class="obst" id="obst1">apple</div>
<div class="obst" id="obst2">orange</div>
<div class="obst" id="obst3">banana</div>
</div>
Upvotes: 1
Reputation: 4246
This soluttion uses a helper function to generate random values and a teplate literal to set the text contents of some div elements.
const
obsts = document.querySelectorAll('.obst'),
limit = obsts.length,
xVals = [],
yVals = [];
// Populates values arrays
for(let i = 0; i < limit; i++){
xVals.push(getRandoBelow(limit));
yVals.push(getRandoBelow(limit));
}
// Populates DOM elements
for(let i = 0; i < limit; i++){
obsts[i].textContent += `x: ${xVals[i]}, y: ${yVals[i]}`;
}
// Generates a random integer below 50
function getRandoBelow(limit){
return Math.floor(Math.random() * 50);
}
.obst{ margin: 0.6em; }
<div>
<div class="obst" id="obst1">obst1 . . . </div>
<div class="obst" id="obst2">obst2 . . . </div>
<div class="obst" id="obst3">obst3 . . .</div>
</div>
Upvotes: 0