How TO - JavaScript HTML Animations

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP




<!--
main_leaderboard, all: [728,90][970,90][320,50][468,60]
-->



How TO - JavaScript HTML Animations



❮ Previous
Next ❯


Learn how to create animations using JavaScript.



Try it Yourself »



A Basic Web Page


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




Example



<!DOCTYPE html>
<html>
<body>

<h1>My First
JavaScript Animation</h1>


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


</body>
<html>

Try it Yourself »





<!--
mid_content, all: [300,250][336,280][728,90][970,250][970,90][320,50][468,60]
-->




Styling the Elements



To make an animation possible, the animated element must be animated relative
to a "parent container".


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


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



Example



#myContainer
    width: 400px;
    height:
400px;
    position: relative;
   
background: yellow;

#myAnimation
    width: 50px;
    height:
50px;
    position: absolute;
   
background: red;

Try it Yourself »



The 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



var id = setInterval(frame, 5);

function frame()
    if (/*
test for finished */)
        clearInterval(id);
     else
       
/* code to change the element style */ 
    




Create the Animation Using JavaScript




Example



function myMove()
    var elem =
document.getElementById("myAnimation");
    var pos = 0;
    var id = setInterval(frame,
10);
   
function frame()
        if (pos ==
350)
           
clearInterval(id);
        else
           
pos++;
           
elem.style.top = pos + 'px';
            elem.style.left = pos + 'px';
       
   


Try it Yourself »




❮ Previous
Next ❯

Popular posts from this blog

WWE Night of Champions

Poznań

Kaliningrad