var myApp = myApp || {}; if (myApp.slideShow) { console.log('myApp.slideShow is already being used'); } else { myApp.slideShow = function(slideShowEl) { var prevSelector = '.prev'; var nextSelector = '.next'; var slideShowContainer = '.slideshow'; var slides = '#items'; var slideWidth = slideShowEl.width(); var activeSlide = slides + ' .active'; var indicators = '#indicator li'; var activeClass = 'active'; var animateSlide = function(index, callback) { slideShowEl .find(slideShowContainer) .stop() .animate({ scrollLeft: index * slideWidth }); if (callback) { callback(); } }; var removeActive = function(callback) { slideShowEl .find('.' + activeClass) .removeClass(activeClass); if (callback) { callback(); } }; var addActive = function(index) { slideShowEl .find(indicators) .eq(index) .addClass(activeClass) .end() .end() .find(slides + ' li') .eq(index) .addClass(activeClass); }; var newSlide = function(index) { if (index < 0) { return false; } else { animateSlide(index, function() { removeActive(function() { addActive(index); }); }); } }; slideShowEl .on('click', prevSelector, function() { newSlide(slideShowEl.find(activeSlide).prev().index()); }) .on('click', nextSelector, function() { newSlide(slideShowEl.find(activeSlide).next().index()); }); }; } $(document).on('ready', function() { myApp.slideShow($('#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; }