www.webdeveloper.com
Results 1 to 4 of 4

Thread: Animating an element right to left and left to right help.

Hybrid View

  1. #1
    Join Date
    Aug 2013
    Posts
    2

    Animating an element right to left and left to right help.

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

    Code:
    <script language="javascript">
    function move() {
      var elem = document.getElementById('example_block');
      var left = 0;
    
      function animate_forward() {
        
        left++;  // update parameters 
        
        elem.style.left = left + 'px'; // show frame 
    
        if (left == 660){  // check finish condition
          clearInterval(id);
    	  animate_backward();
    	  }
    	  function animate_backward(){
    	  	left--;  // update parameters 
        
    		elem.style.left = +left + 'px'; // show frame 
    	
    		if (left == 0){  // check finish condition
    			  clearInterval(id);
    		  }
    	  }
      }
    
      var id = setInterval(animate_forward, 1); // draw every 10ms
    }
    window.onload = move;
    </script>
    
    <div class="example_path">
    	<div id="example_block"></div>
    </div>

  2. #2
    Join Date
    Jun 2008
    Posts
    106
    Your div doesn't move because you have no CSS "position" property set.
    It needs to have a "position" like so:
    Code:
    <div class="example_path">
         <div id="example_block" style="position: absolute; top: 0; left: 0;">text</div>
    </div>
    I made some improvements: http://pastebin.com/49Frdqra
    It's a lot more dynamic and it moves at 30 fps.

    I chose 30 fps because it's a good display interval, and also because yours was too small.
    The minimum interval is 8ms on Firefox and 5ms on Chrome (test at http://jsfiddle.net/FfW9p/)

  3. #3
    Join Date
    Aug 2013
    Posts
    2
    Thank you very muck tenfold. it works.

  4. #4
    Join Date
    Oct 2012
    Location
    Bangalore
    Posts
    2
    as you're working js. you'll not be able to get exact solution of animation. you can shift to jQuery for the good result..

    <script>
    $(document).ready(function() {

    $(".example_path").animate({
    marginLeft: "50%",
    }, 1500 );

    });
    </script>


    so this will work out with ease. 1500 is the speed of movement(animation) in ms. and 50% is the width till where it should animate.

    Thanks & Regards

    Mohammed Ameenulla

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles