Difference between CSS Vs JavaScript Animations

Posted By :Himanshu Khurana |29th May 2018

Most basic animations can be created using CSS or JavaScript, but the workload and time are different. All the advantages and disadvantages, but these are good guidelines:

 

If the UI element has a smaller independent state, use CSS. Transitions and CSS animations are ideal for introducing navigation menus from the side or displaying information about tools. You can eventually use JavaScript to control the state, but the animation itself will exist in your CSS.

 

Use JavaScript when you need important control over the animation. The Web Animation API is a standards-based method that is now available in Chrome and Opera. This provides real objects that are perfect for complex object-oriented applications. JavaScript is also useful when you need to stop, stop, slow down, or rewind.

 

Use requestAnimationFrame directly when manually composing the complete scene. This is an advanced method of JavaScript, but it is useful if you create a game or drawing on an HTML canvas.

 

Animate with CSS

 

Using CSS for animation is the easiest way to perform certain actions on the screen. This method is described as declarative because it specifies what you want to happen.

 

The following is a CSS that moves 100px elements on the X and Y axes. It is done using CSS transformations, which is set to 500 ms. When the movement type is added, the conversion value is changed and the conversion starts.

.demo {
  -webkit-transform: translate(0, 0);
  -webkit-transition: -webkit-transform 500ms;

  transform: translate(0, 0);
  transition: transform 500ms;
}

.demo.move {
  -webkit-transform: translate(100px, 100px);
  transform: translate(100px, 100px);
}  
        

 

Animate using JavaScript and Web Animation APIs

 

In contrast, creating animations using JavaScript is more complicated than writing transformations or CSS animations, but it often provides developers with more features. You can use the Web Animation API to animate specific CSS properties or create compostable effect objects.

 

JavaScript animations are essential because you write them online as part of the code. You can also encapsulate them in other objects. Here's the JavaScript you need to re-create the above CSS conversion:

 

var target = document.querySelector('.box');
var player = target.animate([
  {transform: 'translate(0)'},
  {transform: 'translate(100px, 100px)'}
], 500);
player.addEventListener('finish', function() {
  target.style.transform = 'translate(100px, 100px)';
});
        

 

Thanks


About Author

Himanshu Khurana

Himanshu is an experienced Frontend developer with experience and capabilities to build compelling UI's for Web and Mobile Applications. Himanshu likes playing cricket and listening music.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us