javascript image rotation

Very simple class that rotates images on any event, on any target element (with a preloader).

Click here for an example.

To use it yourself (how the example works):

1. include jquery and the class

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="galleryRotate.js"></script>

2. Instantiate the class with an array of images

$images = ['1.jpg','2.jpg','3.jpg'];
var rotator = new GalleryRotate($images);

3. bind the objects change method to an event, such as mouseclick, telling it the name of target element (always done once the webpage is ready)

$(document).ready(function(){
 
	// click the image
	$('#button').click(function(){
		return rotator.change('#img');
	});
});

Once again an example can be found here.

The full source code can be downloaded here.

The class code is very straight forward and below for completeness.

function GalleryRotate ($images){  
 
	this.preload = function () {
	    $(this.images).each(function(){
	        $('<img/>')[0].src = this;
	    });
	}
 
	this.change = function($element){
 
		$img = this.images[this.imgNo];
 
		if ($element){
			$($element).attr("src", $img);
		}
		else alert($img);
 
		this.imgNo++;
 
		if (this.imgNo==this.images.length){
			this.imgNo=0;
		}
 
		return false;
	}
 
	this.init = function ($images) {
		this.images = $images;
		this.imgNo=0;
		this.preload();	
	}
 
	this.init($images);
}
VN:F [1.9.9_1125]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.9_1125]
Rating: 0 (from 0 votes)

4,845 views

This entry was posted on Monday, January 9th, 2012 at 6:50 pm and is filed under Javascript, Programming. You can follow any responses to this entry through the RSS 2.0 feed.

Leave a Reply