Home > Front End Development, Javascript > jQuery Slideshow Explained

jQuery Slideshow Explained

August 25th, 2009


Homepages generally don’t have enough space for all the promotions clients want to put on there.  The homepage slideshow is a great space saving solution, while keeping your homepage from looking like a dollar store advert.  This post will walk you through the code of a jQuery slideshow.

The Slideshow

Before we start, it might be a good idea to show you the slideshow.  There is nothing too fancy, it has tabs, and it automatically rotates through all the slides.

image

The Code

Now for the meat and potatoes… or what I like to call it, the code.

The CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* background and font colors */
    body{
        background-color: #111;
        color: white;
        font-family: Arial, "MS Trebuchet", sans-serif;
    }
   
    h2{
        color:#8091b0;
    }
   
    /* Define dimensions, and hide anything outside of the div wrapper.
       This is so only the first news story displays as the other
       stories are below the wrapper div if Javascript is shut off.*/

    div#slideShow{
        background:#222;
        width:626px;
        height:200px;
        overflow:hidden;
        position:relative;
    }

    /*Specify a width for each news story */
    div#slideShowItems div{
        width:626px;
    }
   
    /* Make the news story image appear to the left*/
    div#slideShowItems img {
        margin-right:13px;
        float:left;
    }
   
    /* Container for the tabs, the width is set so
       when we float the tabs right they align with the
       edge of the slideshow */

    ul#slideShowCount{
        margin:0px;
        padding:0px;
        width:626px;
    }
   
    /* Float the tabs to the right, and give them a background
       image that looks like a tab. */

    ul#slideShowCount li.slide{
        line-height:14px;
        float:right;
        cursor:pointer;
        width:26px;
        height:18px;
        display:block;
        background: transparent url(tabs.jpg) no-repeat scroll left top;
    }
   
    /* Style the numbers inside of each tab */
    ul#slideShowCount li.slide span{
        padding-left:10px;
        color:white;
        font-weight:bold;
        font-size:12px;
    }
   
    /* Roll over / selected state for the tab */
    /*Shifts background image up, there is a selected state
         below the regular state in the image */

    ul#slideShowCount li.slide:hover,
    ul#slideShowCount li.slide.selectedTab{
        background-position:left -18px;
    }

 

The HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<div id="slideShow">
<div id="slideShowItems">
    <!-- Slide 1 -->
    <div>
        <img alt="" src="image1.jpg" border="0" />
        <h2>Slide 1</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p>
    </div>
   
    <!-- Slide 2 -->
    <div>
        <img alt="" src="image2.jpg" border="0" />
        <h2>Slide 2</h2>
        <p>Laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
   
    <!-- Slide 3 -->
    <div>
        <img alt="" src="image3.jpg" border="0" />
        <h2>Slide 3</h2>
        <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
   
    <!-- Add more tabs as you please.  jQuery will automatically add the tabs for you. -->
</div>
</div>

 

The jQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
* When Everything is loaded */
$(document).ready(function() {

//Setup all the slides.
$('#slideShowItems div').hide().css({position:'absolute',width:'600px'});

var currentSlide = -1; //keeps track of current slide
var prevSlide = null; //keeps track of last selected slide.
var slides = $('#slideShowItems div'); // all the slides
var interval = null; //For setInerval
var FADE_SPEED = 500;  //How long it takes to transition.
var DELAY_SPEED = 15000; //How long each slide stays up.

var html = '<ul id="slideShowCount">';  //Creates a ul list for tabs

//Create a tab for each slide.
for (var i = slides.length - 1;i >= 0 ; i--){
    html += '<li id="slide'+ i+'" class="slide"><span>'+(i+1)+'</span></li>' ;
}
html += '</ul>';

/*
html =

<ul id="slideShowCount">
<li id="slide0" class="slide"><span>1</span></li>
<li id="slide1" class="slide"><span>2</span></li>

</ul>

*/


//Put tabs after slideshow warpper.
$('#slideShow').after(html);


//Set the click event for each tab.
for (var i = slides.length - 1;i >= 0 ; i--){
   
    $('#slide'+i).bind("click",{index:i},function(event){
       
        //Sets the current slide to the one clicked.
        currentSlide = event.data.index;
       
        //Go to the slide.
        gotoSlide(event.data.index);
    });
   
};


//If there is 1 or less slides then hide the tabs.
if (slides.length <= 1){
    $('.slide').hide();
}


//get things started.
nextSlide();


//Goes to the next slide.
function nextSlide (){

    //if the current slide is at the end, loop to the first slide.
    if (currentSlide >= slides.length -1){
        currentSlide = 0;
    }else{
        currentSlide++
    }
   
    //Go to the slide.
    gotoSlide(currentSlide);

}


//Go to the slide specified in the argument.
function gotoSlide(slideNum){

    //If the slide they're trying to access isn't
    //the currently selected slide...
    if (slideNum != prevSlide){

        //The very first slide the prevSlide will be null.
        //No point in trying to hide the slide when it doesn't
        //exist yet.
        if (prevSlide != null){
           
            //Hide previoius slide and deselect old tab.
            $(slides[prevSlide]).stop().hide();
            $('#slide'+prevSlide).removeClass('selectedTab');
        }
       
       
        //Select new tab.
        $('#slide'+slideNum).addClass('selectedTab');

        //Display new slide.
        $(slides[slideNum]).stop().slideDown(FADE_SPEED);
       
        //Make the currentSlide the old slide for next transition.
        prevSlide = currentSlide;

        //if the auto slide advance is set, stop it, then start again.
        if (interval != null){
            clearInterval(interval);
        }
       
        //Goes to next slide every couple of seconds.
        interval = setInterval(nextSlide, DELAY_SPEED);
    }

}
});

 

All the code together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <style type="text/css" media="screen">
    /* background and font colors */
    body{
        background-color: #111;
        color: white;
        font-family: Arial, "MS Trebuchet", sans-serif;
    }
   
    h2{
        color:#8091b0;
    }
   
    /* Define dimensions, and hide anything outside of the div wrapper.
       This is so only the first news story displays as the other
       stories are below the wrapper div if Javascript is shut off.*/
    div#slideShow{
        background:#222;
        width:626px;
        height:200px;
        overflow:hidden;
        position:relative;
    }

    /*Specify a width for each news story */
    div#slideShowItems div{
        width:626px;
    }
   
    /* Make the news story image appear to the left*/
    div#slideShowItems img {
        margin-right:13px;
        float:left;
    }
   
    /* Container for the tabs, the width is set so
       when we float the tabs right they align with the
       edge of the slideshow */
    ul#slideShowCount{
        margin:0px;
        padding:0px;
        width:626px;
    }
   
    /* Float the tabs to the right, and give them a background
       image that looks like a tab. */
    ul#slideShowCount li.slide{
        line-height:14px;
        float:right;
        cursor:pointer;
        width:26px;
        height:18px;
        display:block;
        background: transparent url(tabs.jpg) no-repeat scroll left top;
    }
   
    /* Style the numbers inside of each tab */
    ul#slideShowCount li.slide span{
        padding-left:10px;
        color:white;
        font-weight:bold;
        font-size:12px;
    }
   
    /* Roll over / selected state for the tab */
    /*Shifts background image up, there is a selected state
         below the regular state in the image */
    ul#slideShowCount li.slide:hover,
    ul#slideShowCount li.slide.selectedTab{
        background-position:left -18px;
    }
   
   
    </style>
</head>
<body>
    <div id="slideShow">
        <div id="slideShowItems">
            <!-- Slide 1 -->
            <div>
                <img alt="" src="image1.jpg" border="0" />
                <h2>Slide 1</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p>
            </div>
           
            <!-- Slide 2 -->
            <div>
                <img alt="" src="image2.jpg" border="0" />
                <h2>Slide 2</h2>
                <p>Laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
           
            <!-- Slide 3 -->
            <div>
                <img alt="" src="image3.jpg" border="0" />
                <h2>Slide 3</h2>
                <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
           
            <!-- Add more tabs as you please.  jQuery will automatically add the tabs for you. -->
        </div>
    </div>
</body>
</html>

<!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">

/* When Everything is loaded */
$(document).ready(function() {

//Setup all the slides.
$('#slideShowItems div').hide().css({position:'absolute',width:'600px'});

var currentSlide = -1; //keeps track of current slide
var prevSlide = null; //keeps track of last selected slide.
var slides = $('#slideShowItems div'); // all the slides
var interval = null; //For setInerval
var FADE_SPEED = 500;  //How long it takes to transition.
var DELAY_SPEED = 15000; //How long each slide stays up.

var html = '<ul id="slideShowCount">';  //Creates a ul list for tabs

//Create a tab for each slide.
for (var i = slides.length - 1;i >= 0 ; i--){
    html += '<li id="slide'+ i+'" class="slide"><span>'+(i+1)+'</span></li>' ;
}
html += '</ul>';

/*
html =

<ul id="slideShowCount">
<li id="slide0" class="slide"><span>1</span></li>
<li id="slide1" class="slide"><span>2</span></li>

</ul>

*/

//Put tabs after slideshow warpper.
$('#slideShow').after(html);


//Set the click event for each tab.
for (var i = slides.length - 1;i >= 0 ; i--){
   
    $('#slide'+i).bind("click",{index:i},function(event){
       
        //Sets the current slide to the one clicked.
        currentSlide = event.data.index;
       
        //Go to the slide.
        gotoSlide(event.data.index);
    });
   
};


//If there is 1 or less slides then hide the tabs.
if (slides.length <= 1){
    $('.slide').hide();
}


//get things started.
nextSlide();


//Goes to the next slide.
function nextSlide (){

    //if the current slide is at the end, loop to the first slide.
    if (currentSlide >= slides.length -1){
        currentSlide = 0;
    }else{
        currentSlide++
    }
   
    //Go to the slide.
    gotoSlide(currentSlide);

}


//Go to the slide specified in the argument.
function gotoSlide(slideNum){

    //If the slide they're trying to access isn't
    //the currently selected slide...
    if (slideNum != prevSlide){

        //The very first slide the prevSlide will be null.
        //No point in trying to hide the slide when it doesn't
        //exist yet.
        if (prevSlide != null){
           
            //Hide previoius slide and deselect old tab.
            $(slides[prevSlide]).stop().hide();
            $('#slide'+prevSlide).removeClass('selectedTab');
        }
       
       
        //Select new tab.
        $('#slide'+slideNum).addClass('selectedTab');

        //Display new slide.
        $(slides[slideNum]).stop().slideDown(FADE_SPEED);
       
        //Make the currentSlide the old slide for next transition.
        prevSlide = currentSlide;

        //if the auto slide advance is set, stop it, then start again.
        if (interval != null){
            clearInterval(interval);
        }
       
        //Goes to next slide every couple of seconds.
        interval = setInterval(nextSlide, DELAY_SPEED);
    }

}
});

</script>

 

I tried to comment the code as best as I could. I’ll just give you a quick rundown of the code. The CSS basically sets a width and height for the slideshow, so when it is transitioning between slides it doesn’t jump up and down. We also shove the tabs to the bottom right of the slideshow.

The HTML isn’t too difficult. Each news story is wrapped in a div. If you want to add more stories just create another div and the jQuery wil automatically add the tabs.

The jQuery basically figures out how many divs are within the wrapper, then creates an unordered list of the required tabs. It then creates a click event for each tab. This event just calls a function that switches out the tabs and slides. We also have a function that is called at a set interval if a tab isn’t clicked. It basically just loops through all the slides.

That’s pretty well all there is too it.

 




Top