Background
The below code creates a square box <div class="box">
and adds an animation of different sized circles.
At the moment, the script creates an animation across the whole page, but I’m trying to apply the animation script specifically to the square box <div class="box">
.
I’ve tried changing the script document.body.append(circle)
to document.getElementsByClassName("box")[0].appendChild(circle)
with no success, the animation continues to apply across the whole page.
Question
What code changes are needed to apply the Script animation specifically to <div class="box">
?
Code
<html>
<h1>Heading 1</h1>
<div class="box">
<h2>Heading 2</h2>
<p>This is some text inside a div element.</p>
</div>
<p>This is some text outside the div element.</p>
</html>
<style>
.circle {
position: absolute;
border-radius: 100%;
}
.box {
height: 500px;
width: 500px;
border: 5px outset red;
text-align: center;
}
</style>
<script>
const colors = ["#000000"];
const numCircles = 50;
const circles = [];
for (let i = 0; i < numCircles; i++) {
let circle = document.createElement("div");
circle.classList.add("circle");
circle.style.background = colors[Math.floor(Math.random() * colors.length)];
circle.style.left = `${Math.floor(Math.random() * 100)}vw`;
circle.style.top = `${Math.floor(Math.random() * 100)}vh`;
circle.style.transform = `scale(${Math.random()})`;
circle.style.width = `${Math.random()}em`;
circle.style.height = circle.style.width;
circles.push(circle);
document.body.append(circle);
}
circles.forEach((el, i, ra) => {
let to = {
x: Math.random() * (i % 10 === 0 ? -10 : 10),
y: Math.random() * 10
};
let anim = el.animate(
[
{ transform: "translate(0, 0)" },
{ transform: `translate(${to.x}rem, ${to.y}rem)` }
],
{
duration: (Math.random() + 1) * 2000,
direction: "alternate",
fill: "both",
iterations: Infinity,
easing: "ease-in-out"
}
);
});
</script>
Image