A responsive jQuery carousel is a simple JavaScript carousel that will always fit the browser's viewport width. Creating a responsive jQuery carousel simply means that the outermost container must have a fluid width.
We start with the following markup structure:
<div id="carousel"> <div id="carousel-wrapper"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> <div class="item">4</div> <div class="item">5</div> </div> <div id="carousel-nav"> <a href="#" id="previous">Previous</a> <a href="#" id="next">Next</a> </div> </div>
The outermost container is the element with the ID carousel
. This element must have a fluid width, while the innermost container may have a fixed width. We can accomplish this task by using the max-width
CSS property:
#carousel { width: 100%; max-width: 500px; margin: 2em auto; overflow: hidden; border: 2px solid gray; } #carousel-wrapper { height: 100px; width: 1500px; position: relative; background: silver; } div.item { height: 100%; line-height: 100px; text-align: center; width: 200px; margin-right: 1em; background: yellow; float: left; } #carousel-nav { margin: 1em 0; text-align: center; } #carousel-nav a { color: #fff; background: #000; padding: 0.2em 0.5em; text-decoration: none; margin-right: 1em; }
With jQuery we have only to make the innermost container slide to left or right by using the fixed value of 200 pixels, that is, the width of each carousel's item:
(function($) { if (typeof $.fn.carousel !== 'function') { $.fn.carousel = function(options) { var self = this; var settings = { wrapper: '#carousel-wrapper', item: 'div.item', previous: '#previous', next: '#next', speed: 600 }; options = $.extend(settings, options); var $width = $(options.item).eq(0).width(); return self.each(function() { $(options.previous).click(function(e) { e.preventDefault(); $(options.wrapper).animate({ left: '-=' + $width }, options.speed, 'linear'); }); $(options.next).click(function(e) { e.preventDefault(); $(options.wrapper).animate({ left: '+=' + $width }, options.speed, 'linear'); }); }); }; } })(jQuery); $('#carousel').carousel();
You can see the demo on this page.