I've just started a new project which involves the implementation of a dynamic jQuery slideshow with a progressive pagination made up of several blocks which change their background color according to the current slide index. This is a very common feature on many WordPress themes. Let's see the implementation.
The markup structure is pretty simple:
<div id="slideshow"> <div id="slideshow-wrapper"> <img src="img.jpg" alt=""/> <img src="img.jpg" alt=""/> <img src="img.jpg" alt=""/> <img src="img.jpg" alt="" /> </div> <div id="slideshow-pager"></div> </div>
The slideshow pager block will be populated by jQuery. The trick is to divide the total width of the container by the number of images and use the returned value as the width of each pager element.
Our CSS styles are as follows:
#slideshow { width: 400px; margin: 2em auto; } #slideshow-wrapper { width: 100%; height: 250px; overflow: hidden; background: #999; } #slideshow-wrapper img { float: left; width: 400px; height: 250px; display: none; } #slideshow-pager { height: 10px; background: #ccc; } #slideshow-pager span.pager { height: 10px; float: left; } #slideshow-pager span.pager.active { background: #d34545; }
Each block is initially transparent. Every time an image appears, the CSS class active
will be applied to the current pager block. Here's the jQuery code:
(function($) { var SlideshowPager = { images: $('img', '#slideshow-wrapper'), timer: null, index: -1, create: function() { var $img = this.images; var len = $img.length; var width = $('#slideshow-wrapper').width(); var $width = width / len; for(var i = 0; i < len; i++) { var $span = '<span class="pager"/>'; $($span). css('width', $width) .appendTo('#slideshow-pager'); } }, run: function() { var time = this.timer; var $index = this.index; time = setInterval(function() { $index++; if($index == (SlideshowPager.images.length - 1)) { $index = -1; } $('span.pager', '#slideshow-pager'). eq($index). addClass('active'). siblings('span.pager'). removeClass('active'); $('img', '#slideshow-wrapper'). eq($index). fadeIn(2000) .siblings('img') .hide(); }, 2000); }, init: function() { this.create(); this.run(); } }; $(function() { SlideshowPager.init(); }); })(jQuery);
You can see the demo below.