A featured image slider is an image slider that provides a thumbnail preview of each image. Building a featured image slider is pretty easy with jQuery. All we need to do is to set a couple of CSS style and then add the jQuery behavior. First of all, however, we need to start with a basic markup structure, like the following:
<div id="slider"> <div id="full"> <img src="path/to/img" alt="" /> <!--more images--> </div> <div id="thumbs"> <img src="path/to/img" alt="" /> <!--more images--> </div> </div>
Here are our CSS styles:
#slider { width: 540px; margin: 0 auto; padding: 2em 0; } #full { width: 100%; height: 400px; overflow: hidden; position: relative; } #full img { float: left; width: 100%; height: 100%; } #thumbs { width: 100%; height: 100px; border-top: 0.5em solid gray; border-bottom: 0.5em solid gray; } #thumbs img { float: left; width: 108px; height: 100%; cursor: pointer; }
The main images have been floated so that only the first image is visible. This effect has been achieved thanks to the overflow
property set to hidden
. Now jQuery:
$(document).ready(function() { $('#full img').not(':first').css('width', '1px'); $('#thumbs img').each(function() { var $img = $(this); $img.hover(function() { $img.animate({opacity: '0.8'}, 500); }, function() { $img.animate({opacity: '1'}, 500); }); $img.click(function() { var src = $img.attr('src'); $('#full img').each(function() { var fullImg = $(this); var parentLeft = fullImg.parent().position().left; var fullImgSrc = fullImg.attr('src'); if(fullImgSrc == src) { fullImg.parent().find('img') .not(fullImg).css('zIndex', '0'); fullImg.animate({width: '1px'}, 500) .css({position: 'absolute', zIndex: '1000'}) .animate({ left: 0, width: 540 }, 500); } }); }); }); });
When a user hovers a thumbnail with the mouse, the opacity of the thumbnail is first changed and then restored to the default value. Then, clicking on a thumbnail produces the following effect:
- the width of the corresponding wide image is changed
- the corresponding wide image is absolutely positioned against its parent container.
Point two requires also an adjustment of the z-index
CSS property on each main image. You can see the demo below.