Verification

Contact

Phone
661-203-5357

Email
Kim@KimJoyFox.com

Creating a jQuery Slideshow From Scratch – Part 1

by Kim Joy Fox | September 5, 2012 | jQuery Slideshow, Programmers | Tags: , , ,

jQuery SlideshowThere are tons of pre-made jQuery slideshows out there, but if you’re looking to create your own (whether for the knowledge or for a client), this post series will walk you through the entire process.

We’ll start with the layout and coding a very basic jQuery slideshow. In each additional post, we’ll add in features: navigation, thumbnails, thumbnail navigation, preloading, etc.

We won’t be coding this using Object Oriented Programming, but it will be organized and thought-out in the same way, so it’s a good place to start if you’re trying to make the jump.

jQuery Slideshow Tutorials

What We’re Creating

The slideshow we’re creating in this post is incredibly basic: just one large image, no navigation or thumbnails. It will automatically cycle through the images with no input from the user, and we’ll use jQuery to time it and change the image source.

The HTML & CSS

To create a simple slideshow like this, the only thing we really need is an image on the page with an ID.

<img id="slideshow" alt="" src="source.jpg" />

Then, just to keep our slideshow organized, we’ll add in some qualifications for our image in the CSS file.

#slideshow { max-height:300px; max-width:300px; }

The max-height and max-width statements will let the image keep its dimensions, but won’t let it get too big.

But, if the images might change size, the rest of the items on the page might also move around as the image source changes. So instead of just adding the image, we’re also going to put a Div around that image and give the Div a set height and width.

</pre>
<div id="holder"><img id="slideshow" alt="" src="source.jpg" /></div>
<pre>

 

#holder { height:300px; width:300px; }   //add to CSS file

The jQuery

The jQuery is where the magic really happens.

EDIT: Before you do anything, you’ll need to include the jQuery file – thanks Ken for pointing this out!
At the time of writing this, the most current version is 1.10.2. If you want to find the current version now, check out Google Libraries API.

Include this in the head of your page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

First, we’ll set up an array in Javascript/jQuery to hold the sources for the images.

images = ['http://kimjoyfox.com/wp-content/uploads/drwho8.jpg', 'http://kimjoyfox.com/wp-content/uploads/drwho7.jpg', 'http://kimjoyfox.com/wp-content/uploads/drwho6.jpg', 'http://kimjoyfox.com/wp-content/uploads/drwho5.jpg', 'http://kimjoyfox.com/wp-content/uploads/drwho4.jpg', 'http://kimjoyfox.com/wp-content/uploads/drwho3.jpg'];

Next we’ll write the code that times our slideshow (4000 = 4 seconds):

//this will start the animation automatically
setInterval(forwardImage, 4000);

Now you’ll notice in the coding above that we use the setInterval jQuery function, and then we call another function (that I named forwardImage) within that function. We could just write the actual coding here, but eventually we’ll want to use the coding again (when we add navigation), so we’re going to put it inside of a function.

Notice in line 4 and 6 below, we check to see if we’re at the last image in our images array. “.length” in jQuery returns the total number of items in an array. But watch out! Because arrays start at 0, while counting starts at 1. So to compare the number of items in the array to the current key we’ll need to subtract one.

For example,  the keys of the array number 0-5, but when we count the items in the array, there are 6. So in the coding, we check to see if the current image key (i) is less then 6-1=5. If it less then 5, then we add to i and move forward. Otherwise, we start back over at 0.

//This function will move the slideshow forward one
function forwardImage() {
currentImageKey();
if (i < images.length - 1) {
changeImage(i + 1);
} else {
changeImage(0);
}
}

Within the forwardImage function (above), we call another function: currentImageKey (line 3). We’ll be using this frequently in our coding, so I just put it inside a function. This will tell us what #(key) in the array that we’re on (0-5 for our array).

//This function will find the key for the current Image
function currentImageKey() {
i = jQuery.inArray($('#slideshow').attr('src'), images);
return i;
}

Finally, we add the final function: changeImage (called inside of the forwardImage function, line 5 and 7) that will do the actual heavy lifting of changing the image.

We’re using the animate() jQuery function to change the opacity of the image to 0, and then changing the image source. once the image source is loaded (.load), then we change the slideshow image opacity back to 1. The speed of the animation is controlled on line 5 and 10. 200 equals .2 seconds animation.

//This function will change to image to whatever the variable i passes to it
function changeImage(i) {
$('#slideshow').stop().animate({
opacity: 0,
}, 200, function() {
$('#slideshow').attr('src', images[i]);
$('#holder img').load(function() {
$('#slideshow').stop().animate({
opacity: 1,
}, 200)
})
})
}

And that’s it! Our basic slideshow is done!

See it in action:

SHARE:

SUBSCRIBE TO THE BLOG
Designing Programming Business
Comments
  • Joe says:

    ok so what if I need to have the information stored in the images array, come in from a MySQL database? Can you show me how to integrate the necessary PHP code into this script so that it still functions properly?

    • KimJoyFox says:

      It looks like you got the iteration working (from your other comment on the Thumbnail Navigation). But I’ll be doing a post on this soon!

  • Kirsten says:

    Hi, Kim. I’m just using your code to see if I can get familiar with this process step by step. I get the image to load but it won’t advance to the next image. I used your code exactly as is and I tried referencing images on my own computer. It won’t advance. I’m missing something. Can you help?

  • Charles says:

    Hi Kim. I also used the basic slideshow and I have the same problem as Kirsten stated. Image shows but no slideshow. Here’s my code.

    Some title

    #slideshow { max-height:300px; max-width:300px; }
    #holder { height:300px; width:300px; }

    images = ['../../images/11camry_bro_pg7a.jpg', '../../images/2008_ford_f_150_harley_davidson_wallpaper_ford_cars_wallpaper_1680_1050_widescreen_2485.jpg', '../../images/2010-toyota-sequoia.jpg', '../../images/2012-toyota-camry-inline-3-429-photo-426052-s-original.jpg', '../../images/image3_big.jpg', '../../images/image4_big.jpg'];
    //this will start the animation automatically
    setInterval(forwardImage, 4000);
    //This function will move the slideshow forward one
    function forwardImage() {
    currentImageKey();
    if (i < images.length – 1) {
    changeImage(i + 1);
    } else {
    changeImage(0);
    }
    }
    //This function will find the key for the current Image
    function currentImageKey() {
    i = jQuery.inArray($('#slideshow').attr('src'), images);
    return i;
    }
    //This function will change to image to whatever the variable i passes to it
    function changeImage(i) {
    $('#slideshow').stop().animate({
    opacity: 0,
    }, 200, function() {
    $('#slideshow').attr('src', images[i]);
    $('#holder img').load(function() {
    $('#slideshow').stop().animate({
    opacity: 1,
    }, 200)
    })
    })
    }

    • Ken says:

      What she has failed to mention or at least as best I can tell failed. You have to download a file from jquery.com or org, called jquery-1.10.2.js. There is more than likely a more current version than that. It has to go in the same directory as your html code. Then add the line
      Save and all should be good. :)

  • Charles says:

    It appears you’ve stripped tags but thats the whole basic code. The body section contains the same div as your html with the image source changed to the first element in the images array

  • […] Click here to see the tutorial I used. If you know a little jQuery and are fine with HTML and CSS, it should be easy to follow. It was certainly the most novice-friendly one I could find out there! […]

  • Jamie says:

    I Have a question. How do you link to your javascript that you’ve programmed is it like

    also how do you set up an array in Javascript/jQuery ?

    • KimJoyFox says:

      Hey Jamie! Linking to a Javascript/jQuery page is done the same way as linking to the jQuery library; See “The jQuery” section in the article. Just replace the “src” with where your file is.
      The array is actually at the very top of the coding (see the jsFiddle). It’s like this:
      images = ['item1', 'item2'];

  • Tomas says:

    Hi Kim, + thx for this great tutorial!

    I’ve used the slideshow in a page I’m building for a good friend but cannot make the arrow navigation work in work in Explorer… when the left arrow is clicked it doesn’t move the slideshow forward.

    … Is there a solution for this?

    Very best, T

    • KimJoyFox says:

      Tomas,

      I tested it in IE and it is working. Some possibilities – the post above doesn’t actually have the arrows nav. Here’s the post adding that: Adding Arrow Navigation.
      Otherwise, you’ll want to test each section of the code and see if it’s working.

      1. Are you loading the jQuery library on the page? (I’m assuming yes, but everyone makes this mistake every once in a while :)
      2. Coding enclosed inside of Document.ready() tags?
      3. Add an alert() to the jQuery coding for the arrow nav and see if that fires; if not, double-check IDs.
      4. Are the arrow Div IDs set correctly? Are there any other Div’s on the page with those IDs?
  • Edward says:

    hello kim , thanks for the nice tutorial here.Would like to ask something,how can i display image in array immediately on pageload without the image in the code below

    • KimJoyFox says:

      Do you mean without the slideshow? Just display each image? You’ll be just using “foreach” to cycle through each item in the array.

  • Edward says:

    Div id = “holder”
    img src=”image/slide1.jpg” id=”slideshow

    this is the first image , but i dont want it becoz the navigation button will only work in the image in the array , if i delete it ,it will be a white blank , so how can i get rid of it ?

    • KimJoyFox says:

      So the first image in the image source should be the first image in your array. However, if you don’t want to do that, just add this line at the top of the jQuery, after the setInterval:

      $('#slideshow').attr('src', images[0]);

      I put the image in the HTML so that it loads that image first. That way, when the page is loading there’s a “holder” image for the slideshow.

Leave a Reply

Your email address will not be published.

*



*

Include all code within < code > tags.
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>