jQuery - Creating a Slideshow

Skill

jQuery - Creating a Slideshow

Posted in:

Lately I have been doing a lot with jQuery and one item is a slideshow. Around the web you can find a variety of slideshows, all with slightly different implementations. Well today I am going to add to the already long list with a very simple solution. With the same code you can use this slideshow to display anything you can put into html.

You can check out an example of this below or over at HyperQuake's new site. The example just slides through a few images. I should mention that all of the contents of the slideshow is available at load, so the current implementation would probably not be the best for lots of large images. But for custom html pieces, as with the HyperQuake site, it is very nice because all the content is crawlable and therefore available to search engines for indexing.

To get things rolling we'll take a look at the html for the pretty example above. In the code below you will see a surrounding div (id slideshow-area) which holds our slideshow content scroll area and our next and previous buttons. Inside our scroll area we have a div to hold the content and finally the content itself. As far as html goes this is pretty simple stuff.

<div id="slideshow-area">
  <div id="slideshow-scroller">
    <div id="slideshow-holder">
      <div class="slideshow-content">
        <img src="eureka_small.jpg" />
      </div>
      <div class="slideshow-content">
        <img src="wallace_gromit_small.jpg" />
      </div>
      <div class="slideshow-content">
        <img src="dead_like_me_small.jpg" />
      </div>
    </div>
  </div>
  <div id="slideshow-previous"></div>
  <div id="slideshow-next"></div>
</div>

As I mentioned earlier you can replace the <img with any HTML content you want. That pretty much takes care of the html part.

CSS is up next, it is slightly more complicated than the html but nothing too crazy. The first piece to look at is the positioning and sizing of main slideshow area and scroller, which can have pretty much the same css. We do however add a border to our area to bring it out a little. The code below is fairly understandable, I make sure to set the position to relative so that I can easily position the next and previous buttons absolutely.

#slideshow-area, #slideshow-scroller {
  width: 500px;
  height: 500px;
  position: relative;
  overflow: hidden;
  margin: 0 auto;
}

#slideshow-area {
  border: 1px solid #000;
}

We are also going to set the height of the content holder to 500px, same as the area.

#slideshow-holder {
  height: 500px;
}

The next two items are the previous and next buttons. They take a little bit more work to make sure they are in the correct position. The buttons also have background images for pretty arrows (sorry IE6 users it may look bad since the arrows are png files). I also set the cursor to hand and pointer - for browser compatibility. And finally we also have classes to identify and float left each piece of content in the slideshow.

#slideshow-previous, #slideshow-next {
  width: 50px;
  height: 50px;
  position: absolute;
  background: transparent url("arrow_left.png") no-repeat 50% 50%;
  top: 225px;
  display: none;
  cursor: pointer;
  cursor: hand;
}

#slideshow-next {
  display: block;
  background: transparent url("arrow_right.png") no-repeat 50% 50%;
  top: 225px;
  right: 0;
}

.slideshow-content {
  float: left;
}

Well onto the real work, we now have to create the JavaScript to handle our functionality. jQuery makes this relatively simple though. First item is adding code to the document ready event.

var totalSlides = 0;
var currentSlide = 1;
var contentSlides = "";

$(document).ready(function(){
  $("#slideshow-previous").click(showPreviousSlide);
  $("#slideshow-next").click(showNextSlide);
 
  var totalWidth = 0;
  contentSlides = $(".slideshow-content");
  contentSlides.each(function(i){
    totalWidth += this.clientWidth;
    totalSlides++;
  });
  $("#slideshow-holder").width(totalWidth);
  $("#slideshow-scroller").attr({scrollLeft: 0});
  updateButtons();
});

The code starts out with a few variables that we will use. These hold the total number of slides, what slide we are currently on, and an array of content slides. Our document ready handler starts by adding click event handling to our previous and next buttons. We will define these functions shortly. Next, we figure out the total width of our content by using a simple selector on the slideshow-content class. We then run the results through jQuery's each function adding the widths as we loop through the items and also counting number of slides.

Next we need to create the two functions showPreviousSlide and showNextSlide. These two functions do mainly three things: change current slide number, update the buttons, and scroll the content. These functions along with support functions are below.

function showPreviousSlide()
{
  currentSlide--;
  updateContentHolder();
  updateButtons();
}

function showNextSlide()
{
  currentSlide++;
  updateContentHolder();
  updateButtons();
}

function updateContentHolder()
{
  var scrollAmount = 0;
  contentSlides.each(function(i){
    if(currentSlide - 1 > i) {
      scrollAmount += this.clientWidth;
    }
  });
  $("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1000);
}

function updateButtons()
{
  if(currentSlide < totalSlides) {
    $("#slideshow-next").show();
  } else {
    $("#slideshow-next").hide();
  }
  if(currentSlide > 1) {
    $("#slideshow-previous").show();
  } else {
    $("#slideshow-previous").hide();
  }
}

Starting with the last function, updateButtons, it handles showing and hiding the the appropriate buttons. It looks at what the current slide is and compares it to how many we have or if it is greater than one - pretty easy stuff. The next function is where all the work is done for scrolling our area. We first figure out where we need to scroll to. This is done by adding the width's of the previous slides together. Once the amount is calculated we just need to animate our scroller to the correct place using jQuery's animate function. We pass the attribute to change and how long it should take to do it. With these functions called by our previous and next button clicks we have our slideshow.

That wraps up this tutorial. I hope that at least one person finds something they need from this guy. As always if anyone has any questions feel free to drop us a comment or send us a question through our contact form. Until next time, keep killing time on the Internet.

Update 03/05/2009

I have updated the source code, there was a slight bug when refreshing the page or using the back buttons. This is fixed by resetting the scroll left on the scrolling div and calling an update on the buttons in our document ready function. The code above has been modified. Also here is the updated document ready function.

$(document).ready(function(){
  $("#slideshow-previous").click(showPreviousSlide);
  $("#slideshow-next").click(showNextSlide);
 
  var totalWidth = 0;
  contentSlides = $(".slideshow-content");
  contentSlides.each(function(i){
    totalWidth += this.clientWidth;
    totalSlides++;
  });
  $("#slideshow-holder").width(totalWidth);
  $("#slideshow-scroller").attr({scrollLeft: 0});
  updateButtons();
});

Chris
03/09/2009 - 04:49

This is a great Slideshow! I don't understand how you don't have any comments.

I want to use your slideshow in my project, but there are two features I would love to have.

You have any idea how to make it run by itself on a timer, so that if the user does not click on any of the buttons, it continues to the next picture after a set amount of time? If you can get that to work, do you have any idea how i can get it to pause when the user hovers over it?

Also, I would like to make the arrows show up only when the user hovers over each of them. Is that possible?

Again, great script! I hope you can help me out.

reply

Anonymousa
07/26/2010 - 15:23

You might use one of the jquery timer plugins (http://jquery.offput.ca/every/).
They call your update function on each interval. Use a var to track your current clip and reset (or start at 0) after the last.

reply

Anonymousa
07/26/2010 - 15:24

in doc ready.

window.setInterval('autoScroll()', 4000);

function autoScroll()
{
//currentSlide--;
if(currentSlide <3) {
currentSlide++;
updateContentHolder();
updateButtons(); }
else if (currentSlide == 3) {
currentSlide = 1;
updateContentHolder();
updateButtons();

}
}

reply

Hans
04/02/2009 - 11:50

I agree. Nice script! I looked out for it to be posted a long time a go. Strange thing indeed that there are so little comments.

I also wanted to ask the same thing as Chris: a self sliding slideshow, that stops sliding when hovered on.

@Chris: you can make sure the buttons are only visible when hovered on by changing the background with CSS to something that's not visible (no image or a transparent gif) with CSS. You would need to add something like

#slideshow-next:hover {
background-image: "nonexisting.gif"'
}

Search for the CSS "pseudo classes" (like hover) on the internet. I'm sure you'll find some useful information.

reply

Mark
05/10/2009 - 00:26

I agree, Beautiful simple script!

reply

Richard
07/19/2009 - 05:59

That is absol. brilliant. Thank you ever so much. Works a gem :D

Does anyone know how to add a timer to it aswell. So the image will scroll after about 10 seconds?

reply

xaccrocheur
11/06/2009 - 05:19

... And to add easing, just replace the duration value with :

 
{
     duration: 'slow',
     easing: 'easeOutBounce'
    }

Look here for all easing methods
http://www.learningjquery.com/2009/02/quick-tip-add-easing-to-your-animations

I must say, this implementation is brilliant because it's the only one I know of that takes the scrolled items divs withs and ADD them up to automagically calculate the scroll amount : All the others require the TOTAL width to be hard coded, witch makes no sense in a programmatical environment : Loop and add one div and you're out of bounds. Not so here. Thank you very much, man.

reply

Anonymous
02/26/2010 - 02:42

HI All,

i copy all the code above.
it not working on my testing page.

It show the pic and the arrow but when i click the next pic arrow it do nothing.

Can anyone send me the source which working?
my email is calvinkwoo3000@gmail.com.
Thanks.

reply

gaban
05/28/2010 - 14:47

make sure u put slideshow.css under js file...

reply

Anonymous
06/01/2010 - 06:37

It doesnt work for me iether

reply

minigungunner
06/01/2010 - 07:08

It doesnt work for me iether i have copied it all as it is and it just sticks on the first image. All files and images are in the same folder so there is no reason why it shouldnt work

reply

Ranja
06/07/2010 - 02:24

Hi all,

It works but you have to define the width of content e.g

try it now ... .

reply

Anonymous
08/18/2011 - 08:08

Perfect. What this person means, if you're not getting it, got to this in the css:

.slideshow-content {
float: left;
}

and make it this:

.slideshow-content {
width: 500px;
float: left;
}

reply

marlene
06/24/2010 - 10:34

Hello

I am making a slideshow for a website but it's not working. The image and arrow appear but it's a stand still. Can someone help me please?

marlenelarge@gmail.com

reply

Emily
07/28/2010 - 14:12

Hi. I used your script, but it's not working in Chrome. I didn't change anything. Do you know why that is? Thanks!

reply

Hi
08/05/2010 - 12:45

Thanks for the great script, helps a lot to new JQuery developers.

reply

Anonymous
09/19/2010 - 15:26

Doesn't work on a Safari Browser V5.0.1 on Mac Platform. Get the image and arrow rendered but no response to arrows

reply

Frank
09/26/2010 - 11:45

add this $("#slideshow-scroller").scrollLeft( 0 );

reply

Anonymous
10/06/2010 - 03:54

You have to define the width and height for the slides themselves in the css:

.slideshow-content {
  width: 500px;
  height: 500px;
  float: left;
}

reply

Anonymous
01/26/2011 - 09:35

you need to add jquery file:

you should be able to download the latest version of jquery from their website.

reply

Anonymous
09/21/2010 - 02:03

Doesn't work

reply

The Fattest
11/19/2010 - 11:52

Always good to provide a little more detail than simply "doesn't work".

reply

maximmou
09/25/2010 - 17:59

hey!

how to loop the slideshow?

reply

Sabra
11/16/2010 - 13:18

Great plug-in. Works nicely when using one slideshow on one page, though I have been trying to use this code in 2 separate slide shows within the same page & I can't get it to work. I have even gone so far as duplicating the code (CSS & jQuery) with different ids, variables, function names, etc and it works right up to the point where I change the class name 'slideshow-content'. Once I change this specific class name, the whole thing stops working! This is the one and only piece that I can't seem to change & the one piece that is stopping me from success. What is it about that class name specifically? I am changing the jQuery, CSS & class name simultaneously. Help?

reply

Sia
12/14/2010 - 14:47

Sounds like an amazing script and i would love to use it. For some reason it would not work for me. Any ideas?

here's a test page
http://www.redhookramblers.com/slideshow.html
http://www.redhookramblers.com/slideshow.js
http://www.redhookramblers.com/slideshow.css

sb1932@nyu.edu

reply

Carlos
12/01/2011 - 12:26

<head>


<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Untitled Document</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>

<script type="text/javascript">
    var totalSlides = 4;
    var currentSlide = 2;
    var contentSlides = "";

    $(document).ready(function() {

        var totalWidth = 100;
        contentSlides = $(".slideshow-content");
        window.setInterval('autoScroll()', 4000);

    });

    function autoScroll() {
        //currentSlide--;
        if (currentSlide < 3) {
           currentSlide++;
           updateContentHolder();
           updateButtons();
       }
       else if (currentSlide == 3) {
           currentSlide = 1;
           updateContentHolder();
           updateButtons();

       }
   }

   function showPreviousSlide() {
       currentSlide--;
       updateContentHolder();
       updateButtons();
   }

   function showNextSlide() {
       currentSlide++;
       updateContentHolder();
       updateButtons();
   }

   function updateContentHolder() {
       var scrollAmount = 0;
       contentSlides.each(function(i) {
           if (currentSlide - 1 > i) {
                scrollAmount += this.clientWidth;
            }
        });
        $("#slideshow-scroller").animate({ scrollLeft: scrollAmount }, 1000);
    }

    function updateButtons() {
        if (currentSlide < totalSlides) {
           $("#slideshow-next").show();
       } else {
           $("#slideshow-next").hide();
       }
       if (currentSlide > 1) {
            $("#slideshow-previous").show();
        } else {
            $("#slideshow-previous").hide();
        }
    }

</script>

<style type="text/css">
   
#slideshow-area, #slideshow-scroller {
  width: 500px;
  height: 500px;
  position: relative;
  overflow: hidden;
  margin: 0 auto;
}

#slideshow-holder
{
    height: 500px;
}

#slideshow-previous, #slideshow-next {
        width: 50px;
        height: 50px;
        position: absolute;
        top: 225px;
        display: none;
        cursor: pointer;
        cursor: hand;
        background-image: url(images/arrow_right.png);
        background-color: transparent;
        background-repeat: no-repeat;
        background-position: 50% 50%;
}

#slideshow-next {
        display: block;
        top: 156px;
        right:1px;
        background-color: transparent;
        background-image: url(images/arrow_right.png);
        background-repeat: no-repeat;
        background-position: 50% 50%;
}

.slideshow-content
{
    width: 100%;
         height: 100%;
    float: left;
}

</style>

</head>

<body>
<div id="slideshow-area">
  <div id="slideshow-scroller">
    <div id="slideshow-holder">
      <div class="slideshow-content"> <img src="pork_files/image_band.jpg" alt="band" /> </div>
      <div class="slideshow-content"> <img src="pork_files/busking29may09_1_web.jpg" alt="band"/> </div>
      <div class="slideshow-content"> <img src="pork_files/busking29may09_3_web.jpg" alt="band"/> </div>
      <div class="slideshow-content"> <img src="pork_files/busking29may09_4_web.jpg" alt="band"/> </div>
    </div>
  </div>
  <div id="slideshow-previous"></div>
  <div id="slideshow-next"></div>
</div>

</body>

reply

Q
12/19/2010 - 00:43

Hi,

I've just been trying to figure out your code. It looks like a great source and exactly what I'm looking for. But, I've run into a problem. I have the .css, .js & html files. A picture shows up, but no arrows or ways to move to the next picture. Here's the source files, do you see anything wrong:

http://www.countrygirlwebdesign.com/slideshowtest.html

http://www.countrygirlwebdesign.com/slideshow.js

http://www.countrygirlwebdesign.com/slideshow.css

reply

The Reddest
12/20/2010 - 09:48

Do you have the left and right image files? It doesn't look like they were added to the source section of this post, but here are the links to the files: left arrow and right arrow.

reply

Q
12/19/2010 - 00:44

Oh, my email is qf @ gotdownsyndrome . net (remove spaces)

reply

John Scott
12/22/2010 - 10:41

The code cannot deal with multiple slideshows on one page.

How can i fix this... ?

reply

Anonymous
02/04/2011 - 07:03

This script is nice one ,can anyone help me to take images from single folder ,instead of giving path name for each image ,for this script.

reply

gat
03/25/2011 - 17:47

THis is great. I am using it in my project. Keep it up

reply

Dave
03/29/2011 - 17:22

Hi
This script is exactly what I needed - thank you, although I would like it to loop continuously! I've been looking at this for 2 nights now and can't work it out. Can anyone please help? Thanks in advance.

reply

Chris
03/30/2011 - 11:23

This script is great. Thanks for updating it. Ive added it to my drupal site !

What makes it so cool is that the images do not need to be of the same width to work. All it needs now is a preloaded per image div.

reply

Dan
04/30/2011 - 19:00

Awesome work!
One tiny issue here - the script runs great in Firefox, but not in Chrome.
It appears that in Chrome the images are on top of each other - instead of side by side. Somehow it's not recognizing the float left command... something like that.
I'll do some googling and see if there is a css fix.

Thank you!

reply

Dan
04/30/2011 - 19:05

Yup, I think someone mentioned this here.
Chrome needs a width defined on the content to float both left.
.slideshow-content {
width: 263px;
float: left;
}

Cheers!

reply

Smith Scott
05/05/2011 - 04:41

I am also trying jQuery to Creating a Sideshow but don't understand where I am doing a mistake. I am running a Website Company and daily have to design websites etc. This is the first time getting some error. I need to check the code again and have to encountered the problem. Just going to check the code and have to match this with

$(document).ready(function(){
$("#slideshow-previous").click(showPreviousSlide);
$("#slideshow-next").click(showNextSlide);

var totalWidth = 0;
contentSlides = $(".slideshow-content");
contentSlides.each(function(i){
totalWidth += this.clientWidth;
totalSlides++;
});
$("#slideshow-holder").width(totalWidth);
$("#slideshow-scroller").attr({scrollLeft: 0});
updateButtons();
});

reply

asma
05/05/2011 - 08:28

you need to add jquery.js from www.jquery.com to your website folder ...don't forget add this script <script type="text/javascript" src="jquery.js"></script>
to your main page ...

reply

Anonymous
05/15/2011 - 00:28

Arrows are not visible but slide show works perfectly. What shall i do?

reply

Ollie
05/16/2011 - 13:49

Hi, thanks for the script and updates for chrome and safari.

I'm tryign to incorporate border radius to the slide show.

#slideshow-area {
border: 1px solid #000;
-moz-border-radius: 0 0 30px 30px;
border-radius: 0 0 30px 30px;
}

It works in Friefox, as well as Safari and Chrome, however, the latter two render the radius behind the image.

I tried also adding it to ".slideshow-content" but still no joy.

Do you have any suggestions for fixing this?

reply

latty
06/22/2011 - 16:44

Awesome script.. Works great in facebook HTML static but can't get the same script working in Wordpress... any ideas?

reply

Anonymous
06/29/2011 - 01:47

I don't understand what I am doing wrong.
I followed all of the instructions.

I have the image, I have the arrow, but there is no response when the arrow is clicked.

reply

The Reddest
06/29/2011 - 08:40

Does your browser's javascript error console print anything when the button is pressed?

reply

Neeraj Prasad
07/30/2011 - 05:30

It is a nice script.
I loved it.
I applied in various website and working perfectalyy...
Thanks

reply

Mike G
08/05/2011 - 14:16

Great script - works beautifully in all browsers with the fixes posted by others. Thanks for sharing this!

reply

KIBBEAH!
08/18/2011 - 09:21

This is excellent.

A note for others new to java:

By creating a third div is id=#slideshow-home, then adding this call to the $(document).ready(function():

$("#slideshow-home").click(showFirstSlide);

And this right above the function showPreviousSlide():

function showFirstSlide()
{
currentSlide = 1;
updateContentHolder();
updateButtons();
}

You can create a button that will take you back to the first slide. Similarly, you can create several versions of the above example in order to go to specific slides, changing the "#slideshow-home" and "showFirstSlide" appropriately for each. Then, simply put the numb of the slide you want to go to with that button instead of "1."

reply

Atul
09/22/2011 - 07:56

Instead of images i was trying text and divs are not wrappping the text and therefore functionality is not working as it should...though it is great article no doubt about it...

reply

Carl
10/05/2011 - 11:05

Can you set this slider to automatic slide?

reply

Website Design Company
10/07/2011 - 06:55

can you just provide code for automatic Sliders

reply

Anonymous
10/15/2011 - 14:35

where should those java script code be placed?

reply

Dan
11/09/2011 - 11:51

How can you incorporate this so you can have several slide shows on the same page? They seem to get confused with each other.

reply

Dan
11/09/2011 - 20:51

Got it to work - never mind.

reply

Matt
11/21/2011 - 20:47

Can you link to a specific slide. E.g., if I want to link to the 2nd or 3rd slide, how can I pass that through?

reply

Anonymous
12/29/2011 - 17:40

I am still facing the issues during browswer refresh,
It stay at the last image and does not scroll to the first one when page get refresh
Please find the code i have written

$(document).ready(function(){
alert('inside ready');
$("#slideshow-previous").click(showPreviousSlide);
$("#slideshow-next").click(showNextSlide);

var totalWidth = 0;
contentSlides = $(".slideshow-content");
contentSlides.each(function(i){
alert('setting width');
totalWidth += this.clientWidth;
totalSlide++;
});

/*Even this line of code is not working
$("#slideshow-scroller").scrollLeft(0);
*/
$("#slideshow-holder").width(totalWidth);
$("#slideshow-scroller").attr({scrollLeft: 0});
updateButtons();
});

reply

Hector
01/13/2012 - 15:52

Has anyone figured out how to auto-slide

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.