Create a CSS/jQuery Image Rotator with Descriptions

by Jake Rocheleau

on September 2, 2013

in Tutorials

This original tutorial was created by Soh Tanaka and published back in 2009. Unfortunately his demo has since gone offline and I managed to find an old copy of the source codes. People in the comments have been asking for automatic rotation between the slides and I updated the codes with this feature.

So in this tutorial I am reintroducing some of Soh’s original codes on how to build this dynamic automatic rotator. The jQuery is contained within the same index file and it is easy to follow along. It should also work even running the latest copy of jQuery on your website. Feel free to download a copy of the updated source codes or check out my live demo from the links below.

jquery image rotator tutorial preview screenshot

Getting Started

First we need to create a new document index.html which contains the slider and the JavaScript. I’ll be including a local copy of jQuery but we could also use the CDN-hosted version instead.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Image Rotator w/ Desc - CSS & jQuery Tutorial</title>
  <link rel="shortcut icon" href="http://designm.ag/favicon.ico">
  <link rel="icon" href="http://designm.ag/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
<script type="text/javascript" src="js/jquery.js"></script>
</head>

The document is written using HTML5 schema with only two external files. The jQuery library from the original tutorial is v1.3.2 which is a much older copy. But I tested by replacing with the jQuery v1.10.1 and it still works fine. The main codes do not change much from different releases but you can update the animations in any way you like.

Now the internal HTML is a bit easier to understand as it is broken into smaller div blocks. We can find a single div with the class .main_image which contains the bigger picture you see on the left. It also has blocks for the description text which gets re-animated for each new slide.

<div id="main" class="container">
	<div class="main_image">
		<img src="images/banner01.png" alt="- banner1" />
		<div class="desc">
			<a href="#" class="collapse">Close Me!</a>
			<div class="block">
				<h2>Luigi's Mansion</h2>
				<small>08/27/2013</small>
				
				<p>Autem conventio nimis quis ad, nisl secundum sed, facilisi, vicis augue regula, ratis, autem. Neo nostrud letatio aliquam validus eum quadrum, volutpat et.<br /><a href="http://dribbble.com/shots/1212598-Luigi-s-Mansion" target="_blank">Artwork By Glenn Jones</a> </p>
			</div>
		</div>
	</div>

Below this we find a collection of smaller blocks which contain the thumbnail image. It also holds a title for the photo along with the publication date. This information is pulled out via jQuery and then appended into the main image container.

<div class="image_thumb">
	<ul>
		<li>
			<a href="images/banner01.png"><img src="images/banner01_thumb.png" alt="Luigi Mansion" /></a>
			<div class="block">
				<h2>Luigi's Mansion</h2>
				<small>08/27/2013</small>
					
				<p>Autem conventio nimis quis ad, nisl secundum sed, facilisi, vicis augue regula, ratis, autem. Neo nostrud letatio aliquam validus eum quadrum, volutpat et.<br /><a href="http://dribbble.com/shots/1212598-Luigi-s-Mansion" target="_blank">Artwork by Scott Balmer</a> </p>
			</div>
		</li>

Now this is just one example of a list item from the full set. But you can get an idea of the formatting which contains the headline, date, and a brief description. This is all contained within a single div using the class .image_thumb which then holds an unordered list.

Design Styles

The CSS stylesheet is fairly typical which does not use a whole bunch of resets. We remove all the original margins and padding from elements using the wildcard selector(*). The main image preview container has a lot of fixed styles to keep everything in order. You may need to adjust these sizes in order for them to blend nicely within your own website.

.main_image {
	width: 598px; height: 456px;
	float: left;
	background: #333;
	position: relative;
	overflow: hidden;
	color: #fff;
}
.main_image h2 {
	font-size: 2em;
	font-weight: normal;
	margin: 0 0 5px;	padding: 10px;
}
.main_image p {
	font-size: 1.2em;
	padding: 10px;	margin: 0;
	line-height: 1.6em;
}
.block small { 
	padding: 0 0 0 20px; 
	background: url(images/icon_cal.gif) no-repeat 0 center; 
	font-size: 1em; 
}
.main_image .block small {margin-left: 10px;}
.main_image .desc{
	position: absolute;
	bottom: 0;	left: 0;
	width: 100%;
	display: none;
}
.main_image .block{
	width: 100%;
	background: #111;
	border-top: 1px solid #000;
}

The list item styles are also fairly typical which include their own hover class. It is built using a class which gets applied via jQuery instead of the typical :hover effect. But this can be easily updated as needed. However the .active class is still necessary to ensure that we can switch between different items automatically.

.image_thumb {
	float: left;
	width: 299px;
	background: #f0f0f0;
	border-right: 1px solid #fff;
	border-top: 1px solid #ccc;
}
.image_thumb img {
	border: 1px solid #ccc; 
	padding: 5px; 
	background: #fff; 
	float: left;
}
.image_thumb ul {
	margin: 0; padding: 0;
	list-style: none;
}
.image_thumb ul li{
	margin: 0; padding: 12px 10px;
	background: #f0f0f0 url(images/nav_a.gif) repeat-x;
	width: 279px;
	float: left;
	border-bottom: 1px solid #ccc;
	border-top: 1px solid #fff;
	border-right: 1px solid #ccc;
}
.image_thumb ul li.hover {
	background: #ddd;
	cursor: pointer;
}
.image_thumb ul li.active {
	background: #fff;
	cursor: default;
}
html .image_thumb ul li h2 {
	font-size: 1.5em; 
	margin: 5px 0; padding: 0;
}
.image_thumb ul li .block {
	float: left; 
	margin-left: 10px;
	padding: 0;
	width: 180px;
}

Building with jQuery

The final piece to this tutorial revolves around the image rotation. The script is fairly lengthy but some of the code is just duplicated into a separate function. I will break it down into segments so that everything is easier to understand.

var intervalId;
var slidetime = 2500; // milliseconds between automatic transitions

$(document).ready(function() {	

	// Comment out this line to disable auto-play
	intervalID = setInterval(cycleImage, slidetime);

	$(".main_image .desc").show(); // Show Banner
	$(".main_image .block").animate({ opacity: 0.85 }, 1 ); // Set Opacity
	$(".image_thumb ul li:first").addClass('active');

All of these codes will execute right when the document has loaded. We create a new interval variable which keeps track of the auto-rotation. You may edit slidetime to be any amount in milliseconds between the individual slides. The line which calls setInterval() may be commented out to disable auto-play. This line of code references a custom function cycleImage() which I will explain a bit later.

	$(".image_thumb ul li").click(function(){ 
		// Set Variables
		var imgAlt = $(this).find('img').attr("alt"); //  Get Alt Tag of Image
		var imgTitle = $(this).find('a').attr("href"); // Get Main Image URL
		var imgDesc = $(this).find('.block').html(); 	//  Get HTML of block
		var imgDescHeight = $(".main_image").find('.block').height();	// Calculate height of block	
		
		if ($(this).is(".active")) {  // If it's already active, then...
			return false; // Don't click through
		} else {
			// Animate the Teaser				
			$(".main_image .block").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() {
				$(".main_image .block").html(imgDesc).animate({ opacity: 0.85,	marginBottom: "0" }, 250 );
				$(".main_image img").attr({ src: imgTitle , alt: imgAlt});
			});
		}
		
		$(".image_thumb ul li").removeClass('active'); // Remove class of 'active' on all lists
		$(this).addClass('active');  // add class of 'active' on this list only
		return false;
		
	}) .hover(function(){
		$(this).addClass('hover');
		}, function() {
		$(this).removeClass('hover');
	});

This larger block of code waits to execute until the user clicks on an internal list item. We first generate some variables to update the big image URL and the internal description HTML. If the current list item is already active then we use return false to stop the function. Otherwise we animate the new content into place and then update the .active class onto the new list item.

You’ll also notice towards the bottom we are using the .hover() event listening method to apply a hover class onto the list item as well. jQuery allows chaining of multiple different events together onto the same selector. Without any excess code this might be read as $(“.image_thumb ul li”).click().hover() which is completely valid syntax.

The brief toggle functions also come afterwards, but this is very basic jQuery which doesn’t need much explanation. Look up the jQuery .slideToggle() method to understand more.

    // Function to autoplay cycling of images
    // Source: http://stackoverflow.com/a/9259171/477958
    function cycleImage(){
    var onLastLi = $(".image_thumb ul li:last").hasClass("active");       
    var currentImage = $(".image_thumb ul li.active");
    
    
    if(onLastLi){
      var nextImage = $(".image_thumb ul li:first");
    } else {
      var nextImage = $(".image_thumb ul li.active").next();
    }
    
    $(currentImage).removeClass("active");
    $(nextImage).addClass("active");
    
		// Duplicate code for animation
		var imgAlt = $(nextImage).find('img').attr("alt");
		var imgTitle = $(nextImage).find('a').attr("href");
		var imgDesc = $(nextImage).find('.block').html();
		var imgDescHeight = $(".main_image").find('.block').height();
					
		$(".main_image .block").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() {
      $(".main_image .block").html(imgDesc).animate({ opacity: 0.85,	marginBottom: "0" }, 250 );
      $(".main_image img").attr({ src: imgTitle , alt: imgAlt});
		});
  };

Now this last function cycleImage() is only used by the automatic slider variable. Remember if you want to disable this functionality just comment out the intervalID variable which calls the setInterval() method. I was searching for a basic solution and found this helpful answer on Stack Overflow. I’ve customized the variables to properly target the elements within this tutorial and it all cycles perfectly even back to the beginning.

Much of the animation code has been duplicated from the original click event handler. onLastLi is a variable which checks if the very last item in the list is currently active. If so then our rotator needs to target the very first item moving back to the beginning. The auto-rotate system only requires a currentImage with a nextImage and it can run indefinitely without delay.

jquery image rotator tutorial preview screenshot

Conclusion

There are many auto-rotating jQuery plugins out there but many have their own pre-formatting interface. This can be great if it matches up with your own layout. But sometimes it is much easier to craft your own rotator from scratch, as we have done here.

I do hope this tutorial can prove useful to other developers who need a solution for dynamic image rotation. Many of the jQuery codes are easy to transport over into your own project if you can update the selectors. Also feel free to download a copy of the tutorial codes and use this demo as a template for structuring your unique image rotator.

Powered by Shutterstock

About Jake Rocheleau

Jake is a digital researcher and writer on many popular design magazines. He frequently writes on topics including web design, user experience, mobile apps, and project management. You can find him all throughout Google and tweeting @jakerocheleau. Connect with Jake on google+