scriptonia

Nov 30 '10

Simple sprite animation using javascript (jQuery).

Today I wrote some parts of code just for showing how to create simple animation using css sprites technics and jQuery.

This is example of animation:

Styles for our container and dog animation div.

 

.dog_container {position:relative; width:150px;}
.dog {height: 30px; width: 35px;position:absolute;}
.dog1 {background: urL(dog.png) no-repeat 0px 0px;}
.dog2 {background: urL(dog.png) no-repeat -40px 0px;}
.dog3 {background: urL(dog.png) no-repeat -85px 0px;}

Javascript code for creating animation:

;(function($){
	$(function(){
		var curr_position = 0;
		var prev_position = 0;
		var animation_steps = 0;
		function start_timer() {
			setTimeout(function() {
				$(".dog").removeClass("dog" + prev_position);
				prev_position = curr_position;
				curr_position += 1;
				if (curr_position >= 4)
					curr_position = 0;
				$(".dog").addClass("dog" + curr_position);
				var left = parseInt($(".dog").css("left").replace("px", "").replace("auto", 0));
				if (left > 100) {
					left = 0;
					animation_steps += 1;
					if (animation_steps > 3) {
						return; // stop any animation.
					}
				}
				$(".dog").css("left", left + 3 + "px");
				start_timer();
			}, 100);
		};
		start_timer();
	});
})(jQuery);

As you can we have just used javascript timer and backgroud positions in the sprite image.

That’s it.

2 notes View comments Tags: jquery programming animation

  1. oivoodoo posted this
Blog comments powered by Disqus