Friday, 19 August 2016

CREATE A SIMPLE ANIMATION (JavaScript HTML DOM Animation)

  To create this animation you need a small amount of experience using css and javascript  because the major work is done by this two but not to worry i have broken this down as simple as possible hope it helps you and dont hesitate to give a comment if it does help you

A SIMPLE WEB LAYOUT PAGE:
     to create our animation we will need to create a simple html page then add our css and javascript am sure you are familiar with this.
<html>
<head></head>
<body>

<div id ="container">
<div id ="animate"></div>
</div>
</body>
</html> 
for an effective run of the animation we need two container one acting as our stage and the other serving as the element thats been animated thats why we have two div tag here

now to CSS
The container element should be created with style = "position: relative".
The animation element should be created with style = "position: absolute".
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: black;
}
#animate {
  width: 400px;
  height: 30px;
  position: absolute;
  background-color: teal;
}




</style>

now this code should give you a box and a line across it at the top

now to the major work(java script):

<script>
function myMove() {
  var elem = document.getElementById("animate");
  var pos = 0;
  var id = setInterval(frame, 5);
  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + 'px';
      
    }
  }
}

</script>
create a function and then
1.first get your element by id
2.set the default position of the animate container to 0
3.set an interval //not compulsory but necessary for nice effect
4.create a function that automatically stop the animate container when the it is equal in size with the container
5.then create a conditional statement that keep increasing the the position from the top till its equal to your container size

finally add a button to your html that call the javascript through the click function
your final code should look like this

<!DOCTYPE html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: black;
}
#animate {
  width: 400px;
  height: 30px;
  position: absolute;
  background-color: teal;
}
</style>
<body>

<p>
<button onclick="myMove()">Click Me</button>
</p>

<div id ="container">
<div id ="animate"></div>
</div>

<script>
function myMove() {
  var elem = document.getElementById("animate");
  var pos = 0;
  var id = setInterval(frame, 5);
  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + 'px';
      
    }
  }
}
</script>

</body>
</html>
and your result should look like this:




Share:

0 comments:

Post a Comment