Issue
I want divs with circles to be created and appear on my page
I made a create function where I randomly choose a color and add a circle class which gives the shape of a circle
But now I have them all created together, and the quantity is what I indicate
How can I make these divs create themselves, let's say every 3 seconds, and the number of them on the page is almost unlimited?
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('id', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
document.body.appendChild(div);
}
createDiv('first');
createDiv('second');
createDiv('third');
createDiv('fourth');
createDiv('fifth');
createDiv('sixth');
createDiv('seventh');
createDiv('eighth');
createDiv('ninth');
createDiv('tenth');
createDiv('eleventh');
createDiv('twelfth');
div {
display: inline-block;
margin: 20px;
}
.circle {
clip-path: circle(50%);
height: 50px;
width: 50px;
margin: 20px;
}
Solution
You can leverage setInterval to run the script every three seconds. Since your id is required, the function I'm running every three seconds below also iterates an i var to leverage and keep unique ids:
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('id', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
document.body.appendChild(div);
}
let i = 0;
const threeSeconds = 3000;
setInterval(() => {
i += 1;
createDiv(`div-${i}`)
}, threeSeconds);
div {
display: inline-block;
margin: 20px;
}
.circle {
clip-path: circle(50%);
height: 50px;
width: 50px;
margin: 20px;
}
Answered By - Alexander Nied
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.