Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!

Untitled

By: thetenfold on Aug 2nd, 2013  |  syntax: None  |  size: 1.85 KB  |  views: 35  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <!DOCTYPE html>
  2. <html>
  3.  
  4. <head>
  5.  
  6. <meta charset="UTF-8">
  7. <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
  8.  
  9. <title>Animating Element</title>
  10.  
  11. <script type="text/javascript">
  12.  
  13. function move() {
  14.     var elem = document.getElementById('example_block'),
  15.         left = 0,
  16.         forward = true,
  17.         fps_30 = 1000 / 30, // 30 fps
  18.         id, amountN,
  19.  
  20.         // editable settings
  21.         max_left = 660,    // the farthest in px it will move to the right
  22.         amount = 2;        // the amount in px it will move each interval (currently 30 fps)
  23.  
  24.     function animate() {
  25.         // add amount if forward is true.
  26.         // if not, subtract 1 by adding negative amount.
  27.         left += forward === true ? amount : amountN;
  28.  
  29.         elem.style.left = left + 'px';
  30.  
  31.         if (left >= max_left && forward === true) {  // check finish condition
  32.             forward = false; // make it go in reverse
  33.         } else if (left <= 0 && forward === false) {
  34.             // comment out the line below if you want it to keep
  35.             // going back and forth
  36.             clearInterval(id);
  37.  
  38.             forward = true;
  39.         }
  40.     }
  41.  
  42.     // get a negative amount to subtract from left
  43.     // for moving the element in reverse
  44.     amountN = amount - amount - amount;
  45.  
  46.     // move 2 pixels every 30th of a second (30 fps)
  47.     id = setInterval(function() {
  48.         // run our animate() function in a separate execution
  49.         // context to minimize delay and drift
  50.         setTimeout(animate, 0);
  51.     }, fps_30); // draw every 10ms
  52. }
  53.  
  54. window.onload = move;
  55.  
  56. </script>
  57.  
  58. <style type="text/css">
  59.  
  60. body {
  61.   background-color: #EEEEEE;
  62.   margin: 0;
  63. }
  64.  
  65. </style>
  66.  
  67. </head>
  68.  
  69. <body>
  70.  
  71. <div class="example_path">
  72.         <div id="example_block" style="position: absolute; top: 0; padding: 20px;">Hello</div>
  73. </div>
  74.  
  75. </body>
  76.  
  77. </html>