🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to JavaScript Notes
Topic #146

DOM Animations


Learn to create HTML animations using JavaScript.


A Basic Web Page

To demonstrate how to create HTML animations with JavaScript, we will use a simple web page:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First
 JavaScript Animation</h1>

<div id="animation">My animation will go here</div>

</body>
</html>

Create an Animation Container

All animations should be relative to a container element.

Example

<div id ="container">
  <div id ="animate">My
 animation will go here</div>
</div>

Style the Elements

The container element should be created with style = "position: relative".

The animation element should be created with style = "position: absolute".

Example

 #container {
  width: 400px;
  height:
 400px;
  position: relative;

 background: yellow;

 }
#animate {
  width: 50px;
  height:
 50px;
  position: absolute;

 background: red;
}

Animation Code

JavaScript animations are done by programming gradual changes in an element's style.

The changes are called by a timer. When the timer interval is small, the animation looks continuous.

The basic code is:

Example

id = setInterval(frame, 5);

function frame() {
  if (/*
 test for finished */) {
    clearInterval(id);
  } else {

 /* code to change the element style */
  }
}

Create the Full Animation Using JavaScript

Example

function myMove() {

  let id = null;

  const elem = document.getElementById("animate");

  let pos = 0;

  clearInterval(id);
  id = setInterval(frame, 5);

 function frame() {
    if (pos ==
 350) {

 clearInterval(id);
    } else {

 pos++;
      elem.style.top = pos + 'px';
      elem.style.left = pos + 'px';

      }
  }
}

Want to go beyond the notes?

Join CodingNow 2.0's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

DOM Animations – FAQs

Quick answers about learning DOM Animations in JavaScript.

This free note from CodingNow 2.0 explains DOM Animations in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on CodingNow 2.0, including DOM Animations, is 100% free with no signup required.
With focused practice, most students grasp DOM Animations in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now