I’m trying to animate letters so they fly in from random positions using JavaScript. It works perfectly. However, when I add a button to the HTML, the animations no longer work as expected—the letters appear in the center instead of flying in from random positions. How can I fix this while keeping the button in the same container?
Here’s my code:
HTML:
<div class="container">
<span class="letter">L</span>
<span class="letter">e</span>
<span class="letter">t</span>
<span class="letter">'</span>
<span class="letter">s</span>
<span class="letter"> </span>
<span class="letter">o</span>
<span class="letter">r</span>
<span class="letter">g</span>
<span class="letter">a</span>
<span class="letter">n</span>
<span class="letter">i</span>
<span class="letter">z</span>
<span class="letter">e</span>
<span class="letter"> </span>
<span class="letter">e</span>
<span class="letter">v</span>
<span class="letter">e</span>
<span class="letter">r</span>
<span class="letter">y</span>
<span class="letter">t</span>
<span class="letter">h</span>
<span class="letter">i</span>
<span class="letter">n</span>
<span class="letter">g</span>
</div>
body {
background-color: #282c34;
color: #fff;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
overflow: hidden;
}
.container {
display: flex;
flex-wrap: wrap;
gap: 5px;
font-size: 2rem;
font-weight: bold;
text-align: center;
position: relative;
}
.letter {
position: relative;
opacity: 0;
animation: flyIn 1.5s ease forwards;
}
button {
position: relative;
margin-top: 20px;
padding: 10px 20px;
background-color: #61dafb;
color: #282c34;
border: none;
border-radius: 5px;
font-size: 1rem;
cursor: pointer;
}
button:focus {
outline: none;
}
button:hover {
background-color: #21a1f1;
}
@keyframes flyIn {
from {
opacity: 0;
transform: translate(var(--random-x), var(--random-y));
}
to {
opacity: 1;
transform: translate(0, 0);
}
}
const letters = document.querySelectorAll('.letter');
function animateLetters() {
letters.forEach((letter, index) => {
// Generate rarndom initial positions
const randomX = (Math.random() - 0.5) * window.innerWidth; // Random X
const randomY = (Math.random() - 0.5) * window.innerHeight; // Random Y
// Apply CSS variables for animation
letter.style.setProperty('--random-x', `${randomX}px`);
letter.style.setProperty('--random-y', `${randomY}px`);
// Add staggered delay for smooth animation
letter.style.animationDelay = `${index * 0.2}s`;
});
}
// Trigger animation on load
animateLetters();