Register now or login here to start promoting your blog and your favourite articles.
jQuery Image Gallery/News Slider with Caption Tutorial
29 Jul 2009 - 39 Comments
A really cool News Slider that uses two scrollers to create very slick effect. It uses scrollTo to scroll both description and image items and it comes with previous, next, play, stop and mouseover events.
Author: kevin | Source: queness
Demonstration Download

Introduction

Until this day, jQuery is still blowing me away with its simplicity and robustness. As you can see, I have been concentrated to produce tutorials about it, and I just couldn't help it! Right, this time, we're going to learn how to create a news slider that come with the following features:

  • Slideshow with Image and description/caption
  • previous, next, pause and play buttons
  • On mouse over, pause the slideshow, and play it on mouse out
  • Sliding effect for both gallery panel and excerpt panel
  • Adjustable slideshow speed
  • And, finally, smarter script that will calculate width and height for the slideshow

We're going to use scrollTo jQuery plugin during the development. A huge thumb up and big thank you to Ariel Flesler who created the plugin.

Existing Tutorials

The following is my previous version of image gallery:
Simple JQuery Image Slide Show with Semi-Transparent Caption

And also, the concept that we'll be using for this gallery, it works about the same with the folowing posts, if you want a better illustrated explanations, you can read:
jQuery Sliding Tab Menu for Sidebar Tutorial, or
Create a Vertical, Horizontal and Diagonal Sliding Content Website with jQuery

Explanation

For this slide show, we will combine two sliding panels together, and use the timer (setInterval function) to animate the whole thing. The image below will able to give you more understanding of the html/css layout.

So, there are several important reminders:

  • The size of the #slider should be the same size with the image
  • The total number of excerpt items must be the same with the total number of Images
  • You must set the width and height for #slider, because the script uses it to calculate the width and height for other elements
  • Z-index/ layer order is very important to make sure everything is displayed correctly
  • Buttons can be removed or styled, if you changed the button id, you have to change it in the script as well.

1. HTML

#mask-excerpt is being set to absolute position and z-index to highest so that it will appear on the #gallery. It's possible to take the excerpt out, and make it something like this: DibuSoft mmdv. Remember, total numer of #gallery items must be the same with total number of #excerpt items.

<div id="slider">

	<div id="mask-gallery">

	<ul id="gallery">
		<li><img src="images/pier1.jpg" width="300" height="186" alt=""/></li>
		<li><img src="images/pier2.jpg" width="300" height="186" alt=""/></li>
		<li><img src="images/pier3.jpg" width="300" height="186" alt=""/></li>

	</ul>
	</div>
	
	<div id="mask-excerpt">
	<ul id="excerpt">
		<li>Cras dictum. Maecenas ut turpis. In vitae erat ac orci dignissim eleifend.</li>

		<li>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</li>
		<li>Nunc quis justo. Sed vel ipsum in purus tincidunt pharetra.</li>
	</ul>
	</div>

</div>

<div id="buttons">
	<a href="#" id="btn-prev">prev</a> 
	<a href="#" id="btn-pause">pause</a> 
	<a href="#" id="btn-play">play</a> 
	<a href="#" id="btn-next">next</a>

</div>

2. CSS

This time, CSS is a bit complicated, therefore, I have added line comments to further elaborate it. Refer the to previous illustration, we have to make sure the z-index/layer order are being set correctly, and also float:left for the #gallery so that the items are arranged horizontally. For the #excerpt, we don't have to set the float, because we want it display vertically.

The arrangement of the items will decide the scrolling direction. The arrangment of items are further elabrated in this tutoria - Create a Vertical, Horizontal and Diagonal Sliding Content Website with jQuery


#slider {

	/* You MUST specify the width and height */
	width:300px;
	height:186px;
	position:relative;	
	overflow:hidden;
}

#mask-gallery {
	
	overflow:hidden;	
}

#gallery {
	
	/* Clear the list style */
	list-style:none;
	margin:0;
	padding:0;
	
	z-index:0;
	
	/* width = total items multiply with #mask gallery width */
	width:900px;
	overflow:hidden;
}

	#gallery li {

		
		/* float left, so that the items are arrangged horizontally */
		float:left;
	}


#mask-excerpt {
	
	/* Set the position */
	position:absolute;	
	top:0;
	left:0;
	z-index:500px;
	
	/* width should be lesser than #slider width */
	width:100px;
	overflow:hidden;	
	
}
	
#excerpt {
	/* Opacity setting for different browsers */
	filter:alpha(opacity=60);
	-moz-opacity:0.6;  
	-khtml-opacity: 0.6;
	opacity: 0.6;  
	
	/* Clear the list style */
	list-style:none;
	margin:0;
	padding:0;
	
	/* Set the position */
	z-index:10;
	position:absolute;
	top:0;
	left:0;
	
	/* Set the style */
	width:100px;
	background-color:#000;
	overflow:hidden;
	font-family:arial;
	font-size:10px;
	color:#fff;	
}

	#excerpt li {
		padding:5px;
	}
	


.clear {
	clear:both;	
}

3. Javascript

We've created a function called newsslider. Each time you call it, it will scroll to the next/prev item. This function accepts a parameter called "prev", if you set it to 1/true, it scrolls to previous item, otherwise, it will scroll to the next item.

To animate the news slider, we use a timer called setInterval function, and you can set the speed by assigning the interval value in miliseconds. It's that simple. Right, the following is the script and as usual, I have put comments in every lines to assist you. :)

	
$(document).ready(function() {

	//Speed of the slideshow
	var speed = 5000;
	
	//You have to specify width and height in #slider CSS properties
	//After that, the following script will set the width and height accordingly
	$('#mask-gallery, #gallery li').width($('#slider').width());	
	$('#gallery').width($('#slider').width() * $('#gallery li').length);
	$('#mask-gallery, #gallery li, #mask-excerpt, #excerpt li').height($('#slider').height());
	
	//Assign a timer, so it will run periodically
	var run = setInterval('newsslider(0)', speed);	
	
	$('#gallery li:first, #excerpt li:first').addClass('selected');

	//Pause the slidershow with clearInterval
	$('#btn-pause').click(function () {
		clearInterval(run);
		return false;
	});

	//Continue the slideshow with setInterval
	$('#btn-play').click(function () {
		run = setInterval('newsslider(0)', speed);	
		return false;
	});
	
	//Next Slide by calling the function
	$('#btn-next').click(function () {
		newsslider(0);	
		return false;
	});	

	//Previous slide by passing prev=1
	$('#btn-prev').click(function () {
		newsslider(1);	
		return false;
	});	
	
	//Mouse over, pause it, on mouse out, resume the slider show
	$('#slider').hover(
	
		function() {
			clearInterval(run);
		}, 
		function() {
			run = setInterval('newsslider(0)', speed);	
		}
	); 	
	
});


function newsslider(prev) {

	//Get the current selected item (with selected class), if none was found, get the first item
	var current_image = $('#gallery li.selected').length ? $('#gallery li.selected') : $('#gallery li:first');
	var current_excerpt = $('#excerpt li.selected').length ? $('#excerpt li.selected') : $('#excerpt li:first');

	//if prev is set to 1 (previous item)
	if (prev) {
		
		//Get previous sibling
		var next_image = (current_image.prev().length) ? current_image.prev() : $('#gallery li:last');
		var next_excerpt = (current_excerpt.prev().length) ? current_excerpt.prev() : $('#excerpt li:last');
	
	//if prev is set to 0 (next item)
	} else {
		
		//Get next sibling
		var next_image = (current_image.next().length) ? current_image.next() : $('#gallery li:first');
		var next_excerpt = (current_excerpt.next().length) ? current_excerpt.next() : $('#excerpt li:first');
	}

	//clear the selected class
	$('#excerpt li, #gallery li').removeClass('selected');
	
	//reassign the selected class to current items
	next_image.addClass('selected');
	next_excerpt.addClass('selected');

	//Scroll the items
	$('#mask-gallery').scrollTo(next_image, 800);		
	$('#mask-excerpt').scrollTo(next_excerpt, 800);					
	
}

4. Pagination Addon Mod

Due to popular demand, I added a function called "goto" which allow you to go to a specific item. The following is the changes list:

  • Added a function called "goto"
  • In the html, you need to add "item class" to the image list and excerpt list. For example, both first image and description must have the same class name called: item1.
  • Added link list for the numbering.

Demonstration

Javascript

Add two functions into the javascript: The first one is for the link, and the second function is to navigate the slider.

	
//Put this inside $(document).ready()
//For link/number button
$('#links a').click(function () {
	//stop the slide show
	clearInterval(run);
		
	//go to the item
	goto($(this).attr('rel'));	
		
	//resume the slideshow
	run = setInterval('newsscoller(0)', speed);	
	return false;
});
	


//Add this function after newslider function
function goto(item) {
	$('#mask-gallery').scrollTo(item, 800);		
	$('#mask-excerpt').scrollTo(item, 800);	
	$(item).addClass('selected');					
}


HTML

Due to time constraint, the javascript won't generate the Link by itself, so you will have to add the links. This is how you should add the code:

  • #gallery list : the first item should call item1, second, item2 and so on.
  • #excerpt list : the first item should call item1, second, item2 and so on.
  • #links : the first link should have an attribute rel set to item1, second, item2 and so on.
	
<div id="slider">

	<div id="mask-gallery">
	<ul id="gallery">
		<li class="item1"><img src="images/pier1.jpg" width="300" height="186" alt=""/></li>
		<li class="item2"><img src="images/pier2.jpg" width="300" height="186" alt=""/></li>
		<li class="item3"><img src="images/pier3.jpg" width="300" height="186" alt=""/></li>
	</ul>
	</div>
	
	<div id="mask-excerpt">
	<ul id="excerpt">
		<li class="item1">Cras dictum. Maecenas ut turpis. In vitae erat ac orci dignissim eleifend.</li>
		<li class="item2">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</li>
		<li class="item3">Nunc quis justo. Sed vel ipsum in purus tincidunt pharetra.</li>
	</ul>
	</div>

</div>

<div id="buttons">
	<a href="#" id="btn-prev">prev</a> 
	<a href="#" id="btn-pause">pause</a> 
	<a href="#" id="btn-play">play</a> 
	<a href="#" id="btn-next">next</a>
</div>
<div id="links">
	<a href="#" rel="item1">1</a>
	<a href="#" rel="item2">2</a>
	<a href="#" rel="item3">3</a>
</div>


<div class="clear"></div>

Conclusion

So, here you go, you've just learnt how to create a news slider for your website. It isn't that hard after breaking it into smaller chucks. I hope it helps you to learn more about jQuery.

Last but not least, I need your support :) If you like this article, please help me to promote it by adding this post to your bookmark, subscribe to my RSS for more jQuery tutorial and design inspiration posts! AND also, you can BUY ME A DRINK (link in the footer) to motivate me and keep me awake! Thanks!

Demonstration Download

Copyright & Usage

The effects and techniques demonstrated in tutorials on Queness can be used in whatever manner you wish without attribution. You cannot copy whole tutorials (unless permission is given), either in English or translated to another language.

Share This Post to Support Me! :)


Comments

not2comply on 28 Jul 2009 says:
Excelent work Kevin. I've been messed up for weeks trying to figure it out by myself, and here you are, made 'em easy for us all ;)
Thanks for sharing..
Ezrad Lionel on 28 Jul 2009 says:
I know it\s more work but any gallery that snaps right back to the start instead of \wrapping\ is a fail. Also FU captcha!!
Eric on 28 Jul 2009 says:
This is nice! I was in search of something like this and went the way of the S3Slider....i think that was what is was called.
I then found one other extremely simple method...I do not recall the origin on the one in use on A CLIENT's SITE but it is probably in the midst of my code...just check and see. But this code is set up with the ease of editing the information...so I am going to transit to this Slider...
KEVIN QUE ARE THE MAN! LOL That was just cheezy! LOL
IN OTHER WORDS>>> THANK YOU!
dlv on 29 Jul 2009 says:
i love it! it's the way Wordfolio (wordpress theme on themeforest marketplace) play.

Excellent, thanks for share as always... i love this site !
didxga on 5 Aug 2009 says:
thanks a ton for sharing your skills!
c.bavota on 13 Aug 2009 says:
Thanks for the great tutorial. Just one question: Is it at all possible to make the slideshow not have to rewindto the first image one the last image is reach, but instead just move forward to the first image like an infinite loop?
c.bavota on 13 Aug 2009 says:
Man, I need to read my comments before I submit them. The question should read, "Is it at all possible to make the slideshow not have to rewind to the first image once the last image is reached, but instead just move forward to the first image like it was an infinite wrapping loop?"

Sorry about that.
Eric on 14 Aug 2009 says:
Where in the javascript can you add a function that hides the previous link (btn-prev) when it is on the first slide.
Eric on 24 Aug 2009 says:
How can you make it so the arrows keys left and right will change the slide?
Nacho on 25 Aug 2009 says:
Hey how can i change the "excerpt" to be horizontal?

i try it but i get a big mess doing it.
kevin on 25 Aug 2009 says:
Hi Nacho, I believe this will do the work:
Add the float:left in #excerpt
#excerpt {
......
float:left
......
}

the scrolling work according to the way you arrange it LI, at the moment, it's arranged vertically. so, if you put float left, the LI will display in a row. Don't have to worry bout the scrolling direction, the plugin will work itself out of it. Let me know if it works. :)
Nacho on 26 Aug 2009 says:
Thanks kevin but is not working :S i make a few trys and it moves but when i move it dosen't show the other news and sometimes when change the news go back to the original place.

Thanks!
Nacho on 26 Aug 2009 says:
In a few words i want to get something like you did in the "Slide Show" but with the Next, previous, stop and play buttons

Thanks!
kevin on 26 Aug 2009 says:
change the css to:

#excerpt li {
padding:5px 10px 5px 5px;
width:90px;
float:left;
}

#excerpt {
width:400px;
}

I have tested it, should work :)
Nacho on 27 Aug 2009 says:
KEVIN!!! YOU ROCKS!

It works :) Thanks alot!
Eric on 31 Aug 2009 says:
How can you make it so you can use the arrow keys.. left = prev and right = next

is that possible?
kevin on 31 Aug 2009 says:
Hey eric... yes, it's possible for this script.. just a rough concept thou:

$(document).keyup(function(event){
//left arrow, prev
if(event.keycode == 37) {
newsslider(1);
}

//right arrow, next
if(event.keycode == 39) {
newsslider(0);
}
});


finger crossed, should work... :) if it doesn't help me to fix it... :P..

let me know! :)
Jupiter on 8 Sep 2009 says:
Hi kevin...Amazing works...
Am a newbee. So can u please tell me how to use this function into wordpress..pls
pirate on 14 Sep 2009 says:
hey dude thnx alot it was gr8 but I would like to ask if I wanna add like title above and make it move with them as the pics changing ...is that possible ?
Martin on 14 Sep 2009 says:
Love this - very nice; It's perfect except for one minor detail - is it possible to add individual links to each image in the sequence - if there are 6 images I want a "1 2 3 4 5 6" which when linked go to the appropriate image; This in addition to just a "pause/play" link..

Thanks for sharing!
Dm on 17 Sep 2009 says:
I\m asking the same thing as Martin.
Link to appropriate image & ust a \pause/play\ link

tnx a lot guys!
Kyle on 18 Sep 2009 says:
I have created all four files in dreamweaver and I have them all linked including the jquery.js library, however, it isn't working for me. It loads the first image, but none of the buttons work and it doesn't automatically load the next image. I'm new to scripting.
Kyle on 18 Sep 2009 says:
Okay, I didn't know I had to download the jquery.scrollTo.js file. I had everything else in the right places though. Now that I have it working. I have a real scripting question. How could we make this script call the slides directly by their name. The best example that I can give is the slider on the esfootwear.com index. It would be really cool to have the buttons on the slider like eS. Looks like Martin and Dm would also like to know.

Thank you so much!
kevin on 19 Sep 2009 says:
@Dm, Kyle and Martin: Sorry for letting you all waited for so long, I have added the requested feature. Click on the link in "Addon section" for demo. Cheers.
Kyle on 19 Sep 2009 says:
Kevin, thank you again! I also just put the buttons on the slider by using absolute position and top / left. Is this the best way to go about doing that?
Jim on 29 Sep 2009 says:
As far as I can tell, weve accurately copied your demo code to our test page. Issue: The excerpt advances, but the images do not advance.

Gotta be a simple fix. Thanks for the assist.
Greg on 19 Oct 2009 says:
Hi there. I wonder if I could get this comment approved, it contains a link to the few jQuery articles I had worked on. I would like as many people as possible to read my articles - I write mostly for fun. But the democratic nature of the Internet and Google\\s make my hard work unnoticed unless I ask other developers to link to my page. I have also written the jQuery Tetris plugin, the Mona Lisa shuffle plugin, Aladdin keyboard-controllable animation plugin, jquery tabs plugin and few others -- all available at this link: http://www.authenticsociety.com/blog/jQueryPluginTutorial_Beginner

I had also written tutorials about C++, DirectDraw and OpenGL before. They were well received for their thoroughness and the way I explain complex concepts using simple language. The beginners especially appreciate that the most. People who have read my tutorials have sent me emails saying thanks.

Please approve, you will help another dedicated developer and writer!
Ragnar on 28 Oct 2009 says:
I really appreciate the great tutorial, really simple and works like a charm. Well, that is until it comes to the pagination.

For some reason I cant get it working. And I really cant compare mine to your demo, too, cause it seems youre using a different code for it there.

I did everything like told here but it doesnt scroll to the desired item. Instead it starts acting relatively weird: the scroller starts scrolling two items at a time; not to the next item but to the one after it.

Really weird.
Alex on 3 Nov 2009 says:
Thank you very much Kevin for this fantastic tutorial.

I have already change the feel and look of the slider to fit the future new vertion of my web site, plus I have place the CSS and the Javascrips in external files, everything works perfect.

So I was wondering if I can place two sliders in the same page, so I copy paste the HTML code of the slider into the same page, and the second one did not work; I have been investigating about jQuery.noConflict(); but I am in a death end.

Please help me, showing me the right direccion.

Thank you very much in advance...

Alex
kevin on 3 Nov 2009 says:
Hi Alex, yes you can do that. but it will be a big changeover of ids and classes. you see, this is not an plugin. if you need two sliders, you will need to change those id i declare in html to classes or to other names. If you changed it to other names you will have to duplicate the css and perhaps the script as well.
Alex on 3 Nov 2009 says:
Yes, I try that...

First I have change the id in the HTML, that correspond with the CSS, then I copy and paste the .js file and mofify all the #........ that correspond with the HTML and CSS.

but always one does not work, I believe that it is because i need to duplicate the:
jquery.scrollTo
jquery-1.3.1.min
files, but they looks very complex to try, even i make work one of them with the jQuery.noConflict way, but always one does not work.

Do you know any website that has make work two sliders in the same page?, if you do, can you please tell the URL´s for me to study them and find out where is my mistake.

I was thinking to place a totally different slide show, so i will not going to have any conflict withing them but that can increase the size of the web page, so I am not sure what to do yet, do you have any ideas?

I appreciate your help a lot.

Thank you very much.
kevin on 5 Nov 2009 says:
Hi Alex, u dont have to duplicate jquery.scrollto or the jquery framework.... u just have to insert correct classes into my script.
Alex on 6 Nov 2009 says:
Yes, you are so right....I see my mistake now.

I found a slider with mootools that help me to understand how deep I need to modify the javascript.

I have make working 2 sliders of the mootools in the same page and now I am on my way to make 2 of your sliders work in the same page..........thank you man, without your guidance I will not make it.

I will publish the new version of my webpage on January, I post you then for you to tell me what you think.

Thank you very much again

Alex
Mike on 10 Nov 2009 says:
I love the effect Kevin! Awesome job and thanks for writing up the tutorial, plus getting the user additions in there too!

One question though, I think I am trying what Nacho wanted, a horizontal #excerpt and I believe I followed your instructions, but I still get a vertical #excerpt.

Take a look: hxxp://ormazzi.com/2/index-working.html

Thanks again and in advance for any info :)

tutorial blog on 23 Dec 2009 says:
thank. very good
pollution on 28 Dec 2009 says:
Nice one
Atasözleri on 30 Dec 2009 says:
Very very thank, wonderful working. You are perfect this subject..
Carlos on 14 Jan 2010 says:
Thanks for the amazing tutorial once again! i´ve just a "noob" problem i guess, i can´t make it work when i change the isolated css to an external related sheet. any ideas?
Sigilaea on 7 Feb 2010 says:
This is one of the slickest solutions I have found. Nice job.

I do have a question for you. Is it possible to set the image width and height to a percentage rather than hard code pixel dimensions? I am trying to build a fluid web site and I am using RobotNinja's solution for dynamically resizing my images :
http://unstoppablerobotninja.com/entry/fluid-images/

It works great, but I am new to this and I am having a hard time getting your news slider to scale dynamically to match the new screen resolution.

Leave a comment

http://
Subscribe RSS Subscribe RSS, Keep yourself updated with queness latest posts!
Pixel Crayons Buy and Sell Flash Buy and Sell Flash

Buy wholesale computers directly from China at DHgate.com

Discover the tools to build your e-Commerce Site with Netfirms

  •  
  •  
  •  
  •  
  •  

Community News

Recent Comments

Random Posts


View all posts and news Back to top

About the Author

A web designer and developer who is passionate and keen on contributing to the web development industry. Feel free to say hi to me, or follow me on twitter.

Kevin Liew

Partner

  • Web and Designers
  • CSS Style
  • PV.M Garage Blogzine - (Italian)
  • TutsValley
  • Designrfix
  • CoolVibe
  • Web Developer Juice
  • Denbagus
  • Web Hosting Secret Revealed
  • PSD to HTML Conversion
  • BlueHost