var myApp = myApp || {}; if (myApp.slideShow) { console.log('myApp.slideShow is already being used'); } else { myApp.slideShow = { prevSelector: '.prev', nextSelector: '.next', slideShowContainer: '.slideshow', slides: '#items', activeSlide: '#items .active', indicators: '#indicator li', activeClass: 'active', slideShowEl: undefined, animateSlide: function(index, callback) { this.slideShowEl .find(this.slideShowContainer) .stop() .animate({ scrollLeft: index * this.slideShowEl.width() }); if (callback) { callback(); } }, removeActive: function(callback) { this.slideShowEl .find('.' + this.activeClass) .removeClass(this.activeClass); if (callback) { callback(); } }, addActive: function(index) { this.slideShowEl .find(this.indicators) .eq(index) .addClass(this.activeClass) .end() .end() .find(this.slides + ' li') .eq(index) .addClass(this.activeClass); }, newSlide: function(index) { var that = this; if (index < 0) { return false; } else { that.animateSlide(index, function() { that.removeActive(function() { that.addActive(index); }); }); } }, init: function(slideShowEl) { var that = this; that.slideShowEl = slideShowEl; slideShowEl .on('click', that.prevSelector, function() { that.newSlide(slideShowEl.find(that.activeSlide).prev().index()); }) .on('click', that.nextSelector, function() { that.newSlide(slideShowEl.find(that.activeSlide).next().index()); }); } }; } $(document).on('ready', function() { myApp.slideShow.init($('#slideshow')); });
<div id='slideshow' class='container'> <div id='indicator' class='indicators'> <ul> <li class='active'>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> </div> <div class='slideshow'> <ul id='items'> <li class='active'>Slide 1</li> <li>Slide 2</li> <li>Slide 3</li> <li>Slide 4</li> </ul> </div> <div id='controls' class='slideshowControls'> <ul> <li><button class="prev">Prev</button></li> <li><button class="next">Next</button></li> </ul> </div> </div>
.container { width: 300px; margin: 0 auto; overflow: auto; } .slideshow { margin-top: 50px; overflow: hidden; } .slideshow ul { width: 4000px; overflow: hidden; } .slideshow li { float: left; width: 300px; height: 30px; list-style: none; } .slideshowControls { margin-top: 50px; } .slideshowControls li { float: left; margin-right: 10px; list-style: none; } .indicators li { float: left; margin-right: 10px; list-style: none; } .indicators .active { color: red; }