ES6 AnimationAnimations in JavaScript can handle the things that CSS can't. Several elements in JavaScript help to create a complex animation such as Fade effect, Fireworks, Roll-in or Roll-out, etc. By using JavaScript, we can move the DOM elements such as </img>, </div> or any other HTML element. There are two ways to perform animation in JavaScript, which are as follows:
Let us try to elaborate on these methods. setInterval() methodIt is the traditional method of JavaScript for producing animation effects. It relies on the repeated execution of code for making changes in the element frame by frame. If the function show produces a change in element style, then setInterval(show, t) method can be used for producing gradual changes in the style of an element after every time interval. When the time interval is small, then the animation looks continuous. requestAnimationFrame() methodThis method is easy to set up and hard to cancel. It is optimized to perform smooth animation. The loops in it are needed to be created manually, and also the timing needs to be set up manually. This method is not made to be used at specific intervals. This method is designed to loop at 60fps (frames per second) to perform smooth animation. It won't run in the background, and it is also energy efficient. Now, let's see some of the demonstrations of JavaScript Animation. Example-1 In this example, we are implementing a simple animation by using the properties of the DOM object and functions of JavaScript. We use the JavaScript function getElementById() for getting the DOM object and then assign that object into a global variable. Let's understand the simple animation by using the following example. Example Test it NowExample-2 Let's understand another example of JavaScript animation. In this animation, we will use the setTimeout() function of JavaScript. It is obvious that if we are using a setTimeout() function, then to clear the timer, we have to set clearTimeout() function of JavaScript manually. In the above example, we saw how the image moves towards right on every click. Let us try to automate this process with the setTimeout() function of JavaScript. Test it NowImage Rollover with a mouse eventLet's understand another example of animation in which there is an image rollover by a mouse event. When the mouse moves over the image, the HTTP image will change to the second one from the first image. But when the mouse gets moved away from the image, then the original image will be displayed. Example The onMouseOver event handler triggers when the user will move the mouse onto the link, and the onMouseOut event handler gets trigger when the user will move the mouse away from the link. Test it NowNext TopicES5 vs ES6 |