Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials


Animations in JavaScript

Animations

JavaScript animations is used to capture the attention of your users, keep them engaged, and provide them with a great user experience.

Creating an Animation

Step 1:- After creating a container style them. Container elements should have a relative position always, and the animation elements should have an absolute position.

example
<div id ="animation-container">
    <div id ="animation">JavaScript animation will go here</div>
</div>

Step 2:- To create a JavaScript animation, first create a animation container. Container elements should have a relative position always, and the animation elements should have an absolute position.

example
#animation-container {
	width: 300px;
	height: 300px;
	position: relative;
	background: yellow;
}
#animation {
	width: 30px;
	height: 30px;
	position: absolute;
	background: red;
}

Step 3:- Animations in JavaScript can be easily done by gradual changes in an element's style. The changes are called by a timer. Continuous JavaScript animations can be achieved by setting a tiny timer interval using the setInterval function.

example
var id = null;
function animationMove() {
	var element = document.getElementById("animation");
	var loc = 0;
	clearInterval(id);
	id = setInterval(frame, 5);
	function frame() {
		if (loc == 350) {
			clearInterval(id);
		} else {
			loc++;
			element.style.top = loc + "px";
			element.style.left = loc + "px";
		}
	}
}

requestAnimationFrame - The Modern Way

requestAnimationFrame is the preferred modern approach for animations. It syncs with the browser's repaint cycle (typically 60fps), resulting in smoother animations and better performance than setInterval.

requestAnimationFrame
const box = document.getElementById('animation');
let position = 0;
let animId;

function animate() {
  position += 2;
  box.style.left = position + 'px';

  if (position < 350) {
    animId = requestAnimationFrame(animate);
  } else {
    cancelAnimationFrame(animId);
    console.log('Animation complete');
  }
}

// Start
requestAnimationFrame(animate);

// Stop manually
// cancelAnimationFrame(animId);

CSS Transitions via JavaScript

You can trigger CSS transitions by toggling classes with JavaScript - this is often the cleanest approach for simple animations.

CSS Transitions via JS
/* CSS */
.box {
  width: 50px;
  height: 50px;
  background: #e74c3c;
  transition: transform 0.5s ease, opacity 0.5s ease;
}
.box.active {
  transform: translateX(300px) rotate(360deg);
  opacity: 0.5;
}
// JavaScript
const box = document.querySelector('.box');
const btn = document.getElementById('animateBtn');

btn.addEventListener('click', () => {
  box.classList.toggle('active');
});

// Listen for animation end
box.addEventListener('transitionend', () => {
  console.log('Transition finished');
});

Web Animations API

The Web Animations API provides a powerful JavaScript interface to control animations programmatically - including play, pause, reverse, and speed control.

Web Animations API
const element = document.getElementById('animation');

// Keyframes
const keyframes = [
  { transform: 'translateX(0px)', opacity: 1 },
  { transform: 'translateX(300px)', opacity: 0.5 },
  { transform: 'translateX(0px)', opacity: 1 }
];

// Options
const options = {
  duration: 2000,   // 2 seconds
  iterations: 3,    // repeat 3 times
  easing: 'ease-in-out',
  fill: 'forwards'
};

const anim = element.animate(keyframes, options);

// Control
anim.pause();
anim.play();
anim.reverse();
anim.playbackRate = 2; // double speed

anim.onfinish = () => console.log('Animation done!');
Key Takeaways
  • Use requestAnimationFrame instead of setInterval for smoother, more performant animations.
  • requestAnimationFrame automatically pauses when the tab is hidden, saving CPU/battery.
  • CSS transitions triggered by JavaScript class toggling are the simplest approach for basic animations.
  • The Web Animations API gives full programmatic control: play, pause, reverse, and speed.
  • Always call cancelAnimationFrame() to stop a running animation loop.
  • For complex animations, consider libraries like GSAP or Anime.js for better control and cross-browser support.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.