← Back to Chapters

JavaScript DOM Animations

? JavaScript DOM Animations

⚡ Quick Overview

JavaScript DOM animations let you bring pages to life by changing the style and position of HTML elements over time. By combining DOM manipulation with timers like setInterval() or browser APIs like requestAnimationFrame(), you can move, fade, rotate, and transform elements smoothly.

  • Update element styles (like left, opacity, transform) repeatedly.
  • Use timers to control how fast the animation runs.
  • Use CSS transitions for smooth, hardware-accelerated effects.

? Key Concepts

  • DOM Element Selection: Use document.getElementById() to grab elements to animate.
  • Inline Styles: Change properties such as style.left, style.opacity, etc.
  • Timers: setInterval(), setTimeout() for repeated/delayed updates.
  • requestAnimationFrame(): Smooth animations synced with the browser’s refresh rate.
  • CSS Transitions + JS: Use CSS for smooth transitions and JS only to trigger them.
  • Start/Stop Control: Keep references to intervals so you can stop animations.
  • Keyframe Steps: Move in predefined steps using arrays and timeouts.

? Syntax and Theory

At the core of DOM animations is a simple loop:

  1. Select an element.
  2. Change one or more of its style properties.
  3. Repeat the change after a short delay until a condition is met.

Using setInterval():

  • setInterval(callback, delay) calls callback every delay ms.
  • Use clearInterval(timerId) to stop the animation.

Using requestAnimationFrame():

  • Call requestAnimationFrame(fn) and do one animation step inside fn.
  • Call requestAnimationFrame(fn) again from inside fn to keep it going.
  • Browser optimizes the frame rate for smoothness and power saving.

? Code Examples

▶️ Move a Box Horizontally with setInterval()

This example moves a red box from left to right using setInterval() and style.left.

? View Code Example
// Simple horizontal movement using setInterval()
<div id="box" style="width:50px;height:50px;background:red;position:absolute;"></div>
<script>
let pos = 0;
// Get a reference to the box element
const box = document.getElementById("box");
// Run this function every 10ms to update the position
const timer = setInterval(() => {
// Stop when the box reaches 300px from the left
if (pos >= 300) {
clearInterval(timer);
} else {
// Increase the position and apply it to the style
pos++;
box.style.left = pos + "px";
}
}, 10);
</script>

? Fade Out a Box

This example slowly reduces an element’s opacity and hides it after it becomes almost transparent.

? View Code Example
// Box that we will fade out
<div id="fadeBox" style="width:100px;height:100px;background:blue;"></div>
// Button that triggers the fadeOut() function
<button onclick="fadeOut()">Fade Out</button>
<script>
function fadeOut() {
// Get the element to fade
let el = document.getElementById("fadeBox");
// Start with full opacity (1 = fully visible)
let opacity = 1;
// Decrease the opacity every 100ms
let fade = setInterval(() => {
// If very close to invisible, stop and hide the element
if (opacity <= 0.1) {
clearInterval(fade);
el.style.display = "none";
}
// Apply the current opacity value
el.style.opacity = opacity;
// Decrease the opacity for the next step
opacity -= 0.1;
}, 100);
}
</script>

? Rotate a Box with CSS + JS

Here CSS defines a transition on transform and JavaScript simply changes the transform value to trigger a smooth rotation.

? View Code Example
// CSS for a square box with a smooth transform transition
<style>
#box2 {
width: 100px;
height: 100px;
background: purple;
transition: transform 1s ease;
}
</style>
// Box that will be rotated
<div id="box2"></div>
// Button calls rotate() when clicked
<button onclick="rotate()">Rotate</button>
<script>
function rotate() {
// Rotate the box by 45 degrees (transition makes it smooth)
document.getElementById("box2").style.transform = "rotate(45deg)";
}
</script>

⚙️ Smooth Movement with requestAnimationFrame()

This example uses requestAnimationFrame() for a smooth green ball movement.

? View Code Example
// Circular "ball" that will move across the screen
<div id="ball" style="width:50px;height:50px;background:green;position:absolute;border-radius:50%;"></div>
<script>
// Current x-position of the ball
let x = 0;
function animate() {
// Move until the ball reaches 300px
if (x < 300) {
// Increase position to move the ball
x += 2;
document.getElementById("ball").style.left = x + "px";
// Ask the browser to call animate() again on the next frame
requestAnimationFrame(animate);
}
}
// Start the animation
animate();
</script>

? Start / Stop Controlled Animation

Use separate buttons to start and stop an animation by keeping the interval ID in a variable.

? View Code Example
// Box that we will move left to right
<div id="moveBox" style="width:50px;height:50px;background:black;position:absolute;"></div>
// Buttons to start and stop the movement
<button onclick="startMove()">Start</button>
<button onclick="stopMove()">Stop</button>
<script>
// Store the interval ID so we can stop it later
let moveInt;
// Track the current position
let movePos = 0;
function startMove() {
// Create an interval that updates the position every 50ms
moveInt = setInterval(() => {
movePos += 5;
document.getElementById("moveBox").style.left = movePos + "px";
}, 50);
}
function stopMove() {
// Stop the interval so the box stops moving
clearInterval(moveInt);
}
</script>

? Keyframe Step Animation

This example moves an element in discrete steps using an array of positions and setTimeout().

? View Code Example
// Box that jumps between fixed positions
<div id="keyBox" style="width:50px;height:50px;background:orange;position:absolute;"></div>
<script>
// Get the element and define the keyframe positions
const keyBox = document.getElementById("keyBox");
const steps = [0, 100, 200, 300];
// Index to track which step we are on
let i = 0;
function keyframe() {
// As long as there are steps left, move to the next one
if (i < steps.length) {
keyBox.style.left = steps[i] + "px";
i++;
// Wait 300ms before moving to the next step
setTimeout(keyframe, 300);
}
}
// Start the keyframe animation
keyframe();
</script>

? Live Output and Explanation

? What These Animations Do

  • Move Box: The red box glides horizontally as pos increases until it reaches 300px.
  • Fade Out: The blue box becomes more transparent each step and finally disappears with display: none.
  • Rotate Box: The purple box rotates by 45 degrees using a smooth CSS transition.
  • requestAnimationFrame Ball: The green ball moves smoothly across the screen in sync with the display’s refresh rate.
  • Start/Stop: The black box moves only while the interval is running; pressing Stop pauses it.
  • Keyframe Steps: The orange box jumps between fixed positions (0, 100, 200, 300 pixels).

When you copy these snippets into a full HTML page and open it in a browser, each example will animate the corresponding element as described above.

? Interactive Example

Below is a small playground that combines the ideas above. Click Start to move the box, and Reset to bring it back. This is an “example of the examples” so you can see a complete, real animation in one place.

? Live Demo: Moving Box Playground

 
? View Code for Interactive Example
// Area that contains the moving box
<div id="demoArea" style="position:relative;height:80px;border:1px dashed #cbd5f5;overflow:hidden;">
  <div id="demoBox" style="width:40px;height:40px;background:#ef4444;position:absolute;top:20px;left:0;"></div>
</div>
// Buttons to start and reset the animation
<button id="demoStart">Start</button>
<button id="demoReset">Reset</button>
<script>
// Get references to the elements we need
const demoBox = document.getElementById("demoBox");
const demoArea = document.getElementById("demoArea");
const demoStart = document.getElementById("demoStart");
const demoReset = document.getElementById("demoReset");
// Current x-position of the demo box
let demoX = 0;
// Flag to know if the animation is currently running
let demoAnimating = false;
function step() {
// If animation is stopped, do nothing
if (!demoAnimating) return;
// Calculate the maximum x value so the box stays inside
const maxX = demoArea.clientWidth - demoBox.clientWidth;
// If we reached the end, stop the animation
if (demoX >= maxX) {
demoAnimating = false;
return;
}
// Move the box a few pixels to the right
demoX += 3;
demoBox.style.left = demoX + "px";
// Request the next animation frame
requestAnimationFrame(step);
}
// Start button: only start if not already animating
demoStart.addEventListener("click", () => {
if (!demoAnimating) {
demoAnimating = true;
requestAnimationFrame(step);
}
});
// Reset button: stop and move the box back to the start
demoReset.addEventListener("click", () => {
demoAnimating = false;
demoX = 0;
demoBox.style.left = "0px";
});
</script>

? Use Cases

  • Highlighting important content (e.g., bouncing buttons, sliding banners).
  • Creating interactive games and visual effects.
  • Smooth page transitions or loading indicators.
  • Building custom sliders, carousels, and progress bars.

? Tips & Best Practices

  • Prefer transform and opacity for smoother, GPU-accelerated animations.
  • Use requestAnimationFrame() instead of very fast setInterval() for smoother motion.
  • Always stop timers with clearInterval() when the animation is done or no longer needed.
  • Hide fully faded elements with display: none to prevent them from taking up space.
  • Keep your animation logic simple and focused; avoid heavy work inside each frame.
  • Test animations on different screen sizes to ensure they don’t move elements off-screen.

? Try It Yourself

  • Move a red box 200px to the right using setInterval().
  • Create a blue box that fades out on button click.
  • Use requestAnimationFrame() to slide a green ball smoothly across the screen.
  • Add Start/Stop buttons to control the movement of a black box.
  • Animate an orange box in keyframe-like steps using an array of positions.