Over a million developers have joined DZone.

Carousel Array //JavaScript Class

·
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(","), "
Current: " + c.getCurrent(), "
"); for(var i = 9; --i; document.write("Next: ", c.getNext(), "
")); for(var i = 9; --i; document.write("Previous: ", c.getPrevious(), "
"));
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}