Adsense

Friday, August 19, 2011

Move an object using jQuery animate() function


Today, I am going to share a simple code snippet to show you how you can move an object in a webpage using jQuery’s animate() function.

You can click this link to see a demo of this example.

To try out this example, you will need to prepare an image file, e.g. I use one called “picture.gif” in my example and type out the following skeleton code first.

I will assume you are familiar with <div> tags and CSS, and how to set element properties such as absolute positioning and left / top position etc.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>	   
<style>
#canvas {background:white;width: 100%; height: 100%; }
#picture {width:48;height:139;position:absolute; left:0;top:50;}
</style>
<title>Demo jQuery Move object</title>
</head>	
<body>
<div id="canvas">
<img id="picture" src="picture.gif" />
<button id="btnstart">Start</button>
</div>
</body>
</html>

As you can see, I have named the <img> tag which we will move as “picture” and enclose it in a parent <div> tag called canvas which is 100% of the width of the window. I have also placed a button called “btnstart” which will trigger the object to move when the button is clicked.

Now, we will add the jQuery code to respond to the button click. When the button is clicked, we will call the jQuery animate() function will accept FOUR parameters, 1) what we want to animate as the final result – in this case, the left position of the image to be at the end of the window’s width 2) speed of animation – we choose 1500 milliseconds 3) easing function (how the speed of the animation should be changed in the process of animating) 4) callback – what function to call after animation completes.

The complete code looks like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>	   
<style>
#canvas {background:white;width: 100%; height: 100%; }
#picture {width:48;height:139;position:absolute; left:0;top:50;}
</style>
<title>Demo jQuery Move object</title>
</head>	
<body>
<div id="canvas">
<img id="picture" src="picture.gif" />
<button id="btnstart">Start</button>
</div>

<script>    
$("button#btnstart").click(function(){
$("#picture").animate(
{  left: $("#canvas").width()}, 
1500,
"linear",
function(){  
$(this).css("left", 0);                
}
) //end animate
});

</script>
</body>
</html>

jQuery’s animate() function is quite a powerhouse and can be used to perform other types of animations.  If you want to find out what else can you do with it, the tutorial at w3schools are always highly recommended! Pin It

No comments:

Post a Comment