Animation is a key element that makes modern websites more lively and engaging. It enhances the user experience, highlights important elements, and transforms static interfaces into dynamic, captivating environments.
In this section, we’ll explore how to create animations using JavaScript, covering basic methods and practical examples.
In JavaScript, there are three main ways to create animations:
One of the most popular methods is using CSS animations (or transitions) in conjunction with JavaScript.
Here, animations are defined in CSS, while JavaScript simply triggers them. This results in more structured, readable code.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body, html {
overflow: hidden;
}
#moon {
width: 200px;
height: 200px;
position: absolute;
top: 50%;
transform: translateY(-50%);
transition: opacity 0.3s ease, transform 0.3s ease;
}
#moon.animate {
transform: translateX(550px) translateY(-50%) scale(1.5);
}
.btn {
position: relative;
padding: 12px 20px;
border-radius: 30px;
border: 0;
background-color: black;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<div id="moon"></div>
<button class="btn btn--black btn--medium animateBtn">Start animation</button>
<script>
const moon = document.getElementById('moon');
const button = document.querySelector('.animateBtn');
button.addEventListener('click', () => {
moon.classList.toggle('animate');
});
</script>
</body>
</html>
The second approach involves directly modifying an element’s styles via JavaScript. This method offers more flexibility, allowing you to dynamically change values based on user input or other data.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#moon {
width: 200px;
height: 200px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div id="moon"></div>
<script>
const moon = document.getElementById('moon');
let time = 0;
const moonSize = moon.offsetHeight;
const windowWidth = window.innerWidth;
requestAnimationFrame(animate);
function animate() {
time += 0.009;
// Get a new position
const currentX = time * 100;
if (currentX <= windowWidth - moonSize) {
moon.style.left = `${currentX}px`;
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate); // Start animation
</script>
</body>
</html>
Explanation:
Here, we animate a circle that moves horizontally by altering theleft property in JavaScript. TherequestAnimationFramemethod ensures smooth motion, synchronizing the animation with the screen’s refresh rate, which not only enhances performance but also conserves resources.
requestAnimationFrame is a built-in browser method specifically designed for smooth animations. It’s more efficient than timers like setInterval or setTimeout because it runs in sync with the screen’s refresh cycle.
Example of smooth animation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#moon {
width: 200px;
height: 200px;
background-color: orange;
position: absolute;
overflow: hidden;
}
</style>
</head>
<body>
<div id="moon"></div>
<script>
const moon = document.getElementById('moon');
let time = 0;
const moonSize = moon.offsetHeight;
const amplitude = -moonSize;
const windowWidth = window.innerWidth;
const windowHeightHalf = window.innerHeight / 2;
const centeredY = window.innerHeight / 2 - moonSize / 2
requestAnimationFrame(animate);
function animate() {
time += 0.009;
// Get a new position
const currentX = time * 100;
const currentY = Math.sin(time) * amplitude + centeredY;
if (currentX <= windowWidth - moonSize) {
moon.style.transform = `translate3d(${currentX}px, ${currentY}px, 0)`; // Set a new value
requestAnimationFrame(animate); // Start it again until we reach the goal
}
}
requestAnimationFrame(animate); // Start animation
</script>
</body>
</html>
Explanation:
Conclusion
JavaScript animations are a powerful tool for creating dynamic user interfaces. Whether you’re using simple CSS animations or more complex ones with requestAnimationFrame, it’s essential to ensure that they enhance the user experience without distracting from the website’s core functionality.