Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Carousel Array //JavaScript Class

DZone's Guide to

Carousel Array //JavaScript Class

·
Free Resource
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:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}