#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Posts
    4
    Rep Power
    0

    Javascript animating a element right to left.


    Hi, i am quite new to javascript. i am trying to animate a div tag right to left by using onload function. i have written my code below. Please help somebody to fix this.

    Code:
    <script language="javascript">
    function move() {
      var elem = document.getElementById('example_block');
      var left = 0;
    
      function animate_forward() {
        
        left++;  
        
        elem.style.left = left + 'px'; // show frame 
    
        if (left == 660){  
          clearInterval(id);
    	  animate_backward();
    	  }
    	  function animate_backward(){
    	  	left--;  
        
    		elem.style.left = +left + 'px'; 
    	
    		if (left == 0){  
    			  clearInterval(id);
    		  }
    	  }
      }
    
      var id = setInterval(animate_forward, 1); 
    }
    window.onload = move;
    </script>
    
    <div class="example_path">
    	<div id="example_block"></div>
    </div>
    Last edited by Kravvitz; August 2nd, 2013 at 10:13 PM. Reason: added [code] tags
  2. #2
  3. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,158
    Rep Power
    184
    Your code needed quit a bit of work; so I altered it, to give you a basic example of how to do this:
    Code:
    <style>
    #example_block {
    position:absolute;
    }
    </style>
    
    <script>
    
    var id, id2;
    
    var left = 0;
    
    function animate_forward()
    {
    left++;
    var elem = document.getElementById('example_block');
    elem.style.left = left + 'px'; // show frame
     if (left <= 659){
      id = setTimeout("animate_forward()", 1);
     }
     else {
      id = clearTimeout(id);
      animate_backward();
     }
    document.getElementById("movement").innerHTML = "forward!";
    }
    
    function animate_backward()
    {
    left--;
    var elem = document.getElementById('example_block');
    elem.style.left = left + 'px'; // show frame
     if (left >= 0){
      id2 = setTimeout("animate_backward()", 1);
     }
     else {
      id2 = clearTimeout(id2);
      animate_forward();
     }
    document.getElementById("movement").innerHTML = "backward!";
    }
    
    window.onload = function(){
    animate_forward();
    }
    
    </script>
    
    <div id="example_block">see it move <span id="movement">forward!</span></div>
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Posts
    4
    Rep Power
    0
    Thank you very much, it works.

IMN logo majestic logo threadwatch logo seochat tools logo