Skip to content

ES6 - Animation

JavaScript can be used to create animations on a web page by dynamically changing the properties of DOM elements over time. This can range from simple movements and fade effects to more complex sequences. While CSS Animations and Transitions are often preferred for performance and simplicity for many common effects, JavaScript provides greater control for complex programmatic animations.

JavaScript provides timing functions that are essential for animations:

  • setTimeout(callbackFunction, delayInMilliseconds): Executes callbackFunction once after delayInMilliseconds have passed.
  • setInterval(callbackFunction, intervalInMilliseconds): Repeatedly executes callbackFunction every intervalInMilliseconds.
  • clearTimeout(timeoutID): Cancels a timeout previously established by calling setTimeout(). timeoutID is the value returned by setTimeout().
  • clearInterval(intervalID): Cancels a timed, repeating action previously established by calling setInterval(). intervalID is the value returned by setInterval().
  • requestAnimationFrame(callbackFunction): Tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. This is the preferred method for JavaScript-driven animations as it’s optimized for smoothness and battery life.

Animations are typically achieved by changing an element’s CSS properties, such as left, top, opacity, transform, etc., over time.

// Set distance from left edge (assuming position is 'absolute', 'relative', or 'fixed')
// object.style.left = '100px';
// Set opacity for fade effects
// object.style.opacity = '0.5';

This example shows how to move an image to the right each time a button is clicked.

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Manual Animation</title>
<style>
#myImage { position: relative; left: 0px; top: 0px; transition: left 0.5s ease; /* Optional: for smoother visual transition */ }
</style>
</head>
<body>
<img id="myImage" src="https://via.placeholder.com/50" alt="Placeholder Image">
<p>Click button below to move the image to the right.</p>
<button id="moveButton">Move Right</button>
<script>
const imgObj = document.getElementById('myImage');
const moveButton = document.getElementById('moveButton');
// Ensure the element's style.left is initialized if not set by CSS
// Or parse it assuming it's '0px' initially
imgObj.style.left = imgObj.style.left || '0px';
function moveRight() {
let currentLeft = parseInt(imgObj.style.left, 10); // Parse the current left value
imgObj.style.left = (currentLeft + 20) + 'px'; // Increment and set
}
moveButton.addEventListener('click', moveRight);
// Initialize position via JS if needed if not using inline styles or CSS for initial state
// window.onload = () => { imgObj.style.left = '0px'; }; // Example initialization
</script>
</body>
</html>

Output Description:

An image is displayed. Each time the ‘Move Right’ button is clicked, the image moves 20 pixels to the right from its current position. Adding a CSS transition (as shown in the <style> block) can make this movement appear smoother.

Automated Animation with requestAnimationFrame

Section titled “Automated Animation with requestAnimationFrame”

For continuous animations, requestAnimationFrame is the best choice. It synchronizes with the browser’s refresh rate, leading to smoother animations and better performance.

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Automated Animation</title>
<style>
#animatedBox {
position: relative; left: 0px;
width: 50px; height: 50px; background-color: dodgerblue;
}
</style>
</head>
<body>
<div id="animatedBox"></div>
<p>Click buttons below to handle animation.</p>
<button id="startButton">Start</button>
<button id="stopButton">Stop</button>
<script>
const box = document.getElementById('animatedBox');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
let animationId = null; // To store the ID from requestAnimationFrame
function animateBox() {
let currentLeft = parseInt(box.style.left || '0px', 10);
if (currentLeft > 300) { // Move back to start if it goes too far
currentLeft = 0;
}
box.style.left = (currentLeft + 2) + 'px';
animationId = requestAnimationFrame(animateBox); // Continue the animation
}
startButton.addEventListener('click', function() {
if (!animationId) { // Start only if not already running
box.style.left = '0px'; // Reset position before starting
animationId = requestAnimationFrame(animateBox);
}
});
stopButton.addEventListener('click', function() {
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null; // Reset the ID
}
});
</script>
</body>
</html>

Output Description:

A blue box is displayed. Clicking ‘Start’ makes the box move continuously to the right. If it reaches a certain point (300px), it resets to the left and continues. Clicking ‘Stop’ halts the animation. requestAnimationFrame is used for smooth looping.

A common interactive effect is changing an image when the mouse pointer hovers over it.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Rollover</title>
</head>
<body>
<p>Move your mouse over the image:</p>
<img id="rolloverImage" src="https://via.placeholder.com/150/FF0000/FFFFFF?Text=Image1" alt="Image 1">
<script>
const image = document.getElementById('rolloverImage');
const originalSrc = image.src;
const hoverSrc = 'https://via.placeholder.com/150/0000FF/FFFFFF?Text=Image2'; // Different image for hover
// Preload hover image for better user experience
const preloadHoverImage = new Image();
preloadHoverImage.src = hoverSrc;
image.addEventListener('mouseover', function() {
image.src = hoverSrc;
});
image.addEventListener('mouseout', function() {
image.src = originalSrc;
});
</script>
</body>
</html>

Output Description:

An initial image (Image1, red placeholder) is displayed. When the user moves their mouse pointer over this image, it changes to a different image (Image2, blue placeholder). When the mouse moves away, the original image is restored. Preloading the hover image ensures it’s available immediately when needed.

For many animations, especially those that are not heavily dependent on complex JavaScript logic, consider using:

  • CSS Transitions: Simple way to animate changes in CSS properties smoothly over a given duration.
  • CSS Animations: Allow for more complex, keyframe-based animations defined entirely in CSS.
  • Web Animations API (WAAPI): A JavaScript API that provides more direct control over animations, combining the power of JavaScript with the performance benefits of browser-optimized animations. It’s a more modern and powerful alternative to setTimeout/setInterval based animations for complex scenarios.

Choosing the right tool depends on the complexity of the animation and the level of control required.