DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Carousel Array //JavaScript Class

11.17.2008
| 4231 views |
  • submit to reddit
        Nifty way to cycle arrays in carousel mode.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
Carousel = function(data){
	this.data = data;
};
Carousel.prototype = {
	current: 0,
	data: [],
	move: function(n){
		var l = this.data.length;
		return this.data[Math.abs(this.current = (this.current + (n ? 1 : l - 1)) % l)];
	},
	getNext: function(){
		return this.move(1);
	},
	getPrevious: function(){
		return this.move(0);
	},
	getCurrent: function(){
		return this.data[this.current];
	}
};

Example

var c = new Carousel(["A", "B", "C", "D"]);

document.write("Items: " + c.data.join(","), "<br>Current: " + c.getCurrent(), "<br>");
for(var i = 9; --i; document.write("Next: ", c.getNext(), "<br>"));
for(var i = 9; --i; document.write("Previous: ", c.getPrevious(), "<br>"));