Click here to Skip to main content
15,886,840 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm a beginner and I want to make this square ocilate increasing by 50px each time till it reaches a set #of pixels.
HTML
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> 
$(document).ready(function(){
	$("div").animate({left:'50px'});
   $("div").animate({left:'0px'});
   $("div").animate({top:'50px'});
   $("div").animate({top:'0px'});
   $("div").animate({left:'100px'});
   $("div").animate({left:'0px'});
   $("div").animate({top:'100px'});
   $("div").animate({top:'0px'});
   $("div").animate({left:'150px'});
   $("div").animate({left:'0px'});
   $("div").animate({top:'150px'});
   $("div").animate({top:'0px'});
   $("div").animate({left:'200px'});
   $("div").animate({left:'0px'});
   $("div").animate({top:'200px'});
   $("div").animate({top:'0px'});
});

//loop until reach set value

</script> 
</head>
 
<body>

<div style="background:orange;height:100px;width:100px;removed:absolute;">
</div>

</body>
</html>

I want to achieve the same effect with a function.
Posted
Updated 28-Dec-14 4:18am
v2
Comments
Sergey Alexandrovich Kryukov 27-Dec-14 18:49pm    
And what's the problem looping it? You are doing something opposite to the idea of programming. Never repeat anything. Don't repeat $('div'), calculate it once and same in the variable. And so on...
—SA

1 solution

Try this:
XML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
  var $selector = $('div');
  var displacement = 0;

  for (i=0;i<4;i++){
     displacement += 50;
     $selector.animate({left: displacement});
     $selector.animate({left: 0});
     $selector.animate({top: displacement});
     $selector.animate({top: 0});
  }
});
</script>
</head>
<body>
<div style="position:relative;background:#ff0000;height:100px;width:100px;">
</div>
</body>
</html>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900