HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM Animations

JavaScript can be used to create dynamic animations by gradually changing the style of an element over a sequence of tiny time intervals. This allows for movement, fades, and smooth transitions.


The Animation Concept

To create a basic movement, you typically need a container element and a moving element. The container must have position: relative, and the moving element must have position: absolute.


Method 1: Using setInterval()

The setInterval() method calls a function at specified intervals. By changing a property (like top or left) by 1px every 5 milliseconds, you create the illusion of smooth movement.

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"; 
    }
  }
}

Method 2: requestAnimationFrame()

For modern, professional web development, requestAnimationFrame() is the preferred choice. It tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint.

  • Better Performance: Matches the screen's refresh rate (typically 60fps).
  • Battery Efficiency: Pauses automatically when the user switches to a different tab.

Key Components for Animation

  • Container: Defines the boundary of the movement.
  • Target Element: The item whose styles are changing.
  • Interval/Loop: The engine that drives the frame-by-frame update.
  • Coordinate System: Using top, left, or transform to define position.
Tip: While JavaScript gives you ultimate control, for simple transitions (like hover effects), CSS Transitions are often smoother and perform better because they are hardware-accelerated.

Key Points to Remember

  • Animations are created by changing styles over time
  • position: absolute is essential for coordinate-based movement
  • setInterval() is simple but less efficient for logic-heavy motion
  • requestAnimationFrame() is the gold standard for web performance
  • Always provide a stop condition (like clearInterval()) to prevent memory leaks
  • Use transform: translate() for even smoother hardware-accelerated animation