Advertisement
  1. Code
  2. JavaScript

Build an Auto-Scrolling Slideshow That Works With and Without JavaScript

Scroll to top
Read Time: 9 min

Create a jQuery slideshow that enables you to click through each slide when JavaScript is disabled, without having to display all slides one under the other.



Introduction

Final ProductFinal ProductFinal Product

There are several tutorials that walk people through how to create a jQuery slideshow, but there aren't many
that focus on making it function without JavaScript. This is because most people believe it isn't possible but
I am going to explain an exceedingly simple method that shows it is indeed possible. You'll soon be
kicking yourself and asking "How did I not think of that?"…

In this tutorial I will cover the following:


Step 1: Writing the markup

First things first, we need to write the markup that our slideshow will use. So let's jump straight
in and code it up:

1
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
<html xmlns="http://www.w3.org/1999/xhtml">
5
    <head>
6
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7
        <title>Tabbed jQuery slideshow</title>
8
        
9
        <link rel="stylesheet" href="css/slideshow.css" type="text/css" media="screen" />        
10
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
11
    </head>
12
    <body>
13
        <div id="slideshow">
14
            <div class="slides">
15
                <ul>
16
                    <li>
17
                        <h2>Slide one</h2>
18
                        <p>
19
                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
20
                            Donec pretium arcu non velit. Phasellus adipiscing auctor 
21
                            lorem. Curabitur in urna ut purus consequat sollicitudin. 
22
                            Phasellus ut diam. Cras magna libero, tempor id, venenatis 
23
                            sit amet, venenatis et, dui.
24
                        </p>
25
                    </li>
26
                    <li>
27
                        <h2>Slide two</h2>
28
                        <p>
29
                            Nam ac nibh sit amet augue ultricies sagittis. Donec sit 
30
                            amet nunc. Vivamus lacinia, nisi ac tincidunt commodo, purus 
31
                            nisi condimentum urna, sit amet molestie odio dolor non lectus. 
32
                            Cum sociis natoque penatibus et magnis dis parturient montes, 
33
                            nascetur ridiculus mus.
34
                        </p>
35
                    </li>   
36
                    <li>
37
                        <h2>Slide three</h2>
38
                        <p>
39
                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
40
                            Suspendisse adipiscing dui a nibh. Integer tristique lorem 
41
                            vitae massa. Etiam dapibus, eros sit amet euismod semper, 
42
                            felis erat congue lacus, sed aliquam metus libero sed elit.
43
                        </p>
44
                    </li>                
45
                </ul>
46
            </div>
47
            <ul class="slides-nav">
48
                <li><a href="#">Slide one</a></li>
49
                <li><a href="#">Slide two</a></li>
50
                <li><a href="#">Slide three</a></li>
51
            </ul>
52
        </div>
53
    </body>
54
</html>

This isn't quite complete yet but as a general rule of thumb, we should
always start with the bare minimum and enhance/add to it when
necessary.


Step 2: Add some CSS

We're not going to be creating the most beautiful slideshow today as I
just want to demonstrate the functionality more than anything. The
following styles will set up our slideshow ready for action:

1
2
/* ---------------------------------------------------- */
3
/* GLOBAL

4
/* ---------------------------------------------------- */
5
html {
6
font-size: 76%;}
7
8
body {
9
font-family: arial, helvetica, sans-serif;
10
line-height: 1.4em;
11
font-size: 1.2em;
12
padding: 5%;}
13
14
/* ---------------------------------------------------- */
15
/* SLIDESHOW

16
/* ---------------------------------------------------- */
17
#slideshow {
18
width: 960px;
19
background-color: #eee;
20
border: 1px solid #ddd;}
21
22
#slideshow ul {
23
margin: 0;
24
padding: 0;
25
list-style-type: none;
26
height: 1%; /* IE fix */}
27
28
#slideshow ul:after {
29
content: ".";
30
clear: both;
31
display: block;
32
height: 0;
33
visibility: hidden;}            
34
35
/* ---------------------------------------------------- */
36
/* SLIDESHOW > SLIDES

37
/* ---------------------------------------------------- */
38
#slideshow .slides {
39
overflow: hidden;
40
width: 960px;}
41
42
#slideshow .slides ul {
43
/* total width of all slides -

44
960px multiplied by 3 in this case */
45
width: 2880px;}
46
47
#slideshow .slides li {
48
width: 920px;
49
float: left;
50
padding: 20px;}
51
52
#slideshow .slides h2 {
53
margin-top: 0;}
54
55
/* ---------------------------------------------------- */
56
/* SLIDESHOW > NAVIGATION

57
/* ---------------------------------------------------- */
58
#slideshow .slides-nav {
59
background-color: #ddd;
60
border-top: 2px solid #ccc;}
61
62
#slideshow .slides-nav li {
63
float: left;}
64
65
#slideshow .slides-nav li a {
66
display: block;
67
padding: 15px 20px;
68
outline: none;}

Add these styles to a slideshow.css stylesheet
in a CSS directory within the root. You should now see something
similar to this:

tabstabstabs

Step 3: Making it function without JavaScript

Some of you are probably wondering how on earth this is going to work
by now so I won't make you wait any longer.

All we need to do is give each of our slides an ID and reference that
ID in the href attribute of the appropriate navigation item. It's that
simple.

Your new markup should look as follows:

1
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
<html xmlns="http://www.w3.org/1999/xhtml">
5
    <head>
6
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7
        <title>Tabbed jQuery slideshow</title>
8
        
9
        <link rel="stylesheet" href="css/slideshow.css" type="text/css" media="screen" />        
10
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
11
    </head>
12
    <body>
13
        <div id="slideshow">
14
            <div class="slides">
15
                <ul>
16
                    <li id="slide-one">
17
                        <h2>Slide one</h2>
18
                        <p>
19
                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
20
                            Donec pretium arcu non velit. Phasellus adipiscing auctor 
21
                            lorem. Curabitur in urna ut purus consequat sollicitudin. 
22
                            Phasellus ut diam. Cras magna libero, tempor id, venenatis 
23
                            sit amet, venenatis et, dui.
24
                        </p>
25
                    </li>
26
                    <li id="slide-two">
27
                        <h2>Slide two</h2>
28
                        <p>
29
                            Nam ac nibh sit amet augue ultricies sagittis. Donec sit 
30
                            amet nunc. Vivamus lacinia, nisi ac tincidunt commodo, purus 
31
                            nisi condimentum urna, sit amet molestie odio dolor non lectus. 
32
                            Cum sociis natoque penatibus et magnis dis parturient montes, 
33
                            nascetur ridiculus mus.
34
                        </p>
35
                    </li>   
36
                    <li id="slide-three">
37
                        <h2>Slide three</h2>
38
                        <p>
39
                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
40
                            Suspendisse adipiscing dui a nibh. Integer tristique lorem 
41
                            vitae massa. Etiam dapibus, eros sit amet euismod semper, 
42
                            felis erat congue lacus, sed aliquam metus libero sed elit.
43
                        </p>
44
                    </li>                
45
                </ul>
46
            </div>
47
            <ul class="slides-nav">
48
                <li><a href="#slide-one">Slide one</a></li>
49
                <li><a href="#slide-two">Slide two</a></li>
50
                <li><a href="#slide-three">Slide three</a></li>
51
            </ul>
52
        </div>
53
    </body>
54
</html>

Now test out your new code by clicking each tab… How cool is that?

This is by no means an undiscovered technique. People are already using
it on sites you have probably used without realising, such as the
Coda website.


Step 4: Adding Some Animation

Right well, that was fun! Now it's time to add some funky sliding animations
to our slideshow.

You'll need to download the
minified
jQuery Cycle plugin
that includes all transitions and save it as jquery.cycle.js
within a 'js' directory in your project root. Then add the following to your
<head> below the jquery library script tag.

1
2
<script type="text/javascript" src="js/jquery.cycle.js"></script>
3
<script type="text/javascript" src="js/slideshow.js"></script>

We'll now create the slideshow.js file mentioned above and save it in the
'js' directory with the following code:

1
2
$slideshow = {
3
    context: false,
4
    tabs: false,
5
    timeout: 1000,      // time before next slide appears (in ms)

6
    slideSpeed: 1000,   // time it takes to slide in each slide (in ms)

7
    tabSpeed: 300,      // time it takes to slide in each slide (in ms) when clicking through tabs

8
    fx: 'scrollLeft',   // the slide effect to use

9
    
10
    init: function() {
11
        // set the context to help speed up selectors/improve performance

12
        this.context = $('#slideshow');
13
        
14
        // set tabs to current hard coded navigation items

15
        this.tabs = $('ul.slides-nav li', this.context);
16
        
17
        // remove hard coded navigation items from DOM 

18
        // because they aren't hooked up to jQuery cycle

19
        this.tabs.remove();
20
        
21
        // prepare slideshow and jQuery cycle tabs

22
        this.prepareSlideshow();
23
    },
24
    
25
    prepareSlideshow: function() {
26
        // initialise the jquery cycle plugin -

27
        // for information on the options set below go to: 

28
        // http://malsup.com/jquery/cycle/options.html

29
        $("div.slides > ul", $slideshow.context).cycle({
30
            fx: $slideshow.fx,
31
            timeout: $slideshow.timeout,
32
            speed: $slideshow.slideSpeed,
33
            fastOnEvent: $slideshow.tabSpeed,
34
            pager: $("ul.slides-nav", $slideshow.context),
35
            pagerAnchorBuilder: $slideshow.prepareTabs,
36
            before: $slideshow.activateTab,
37
            pauseOnPagerHover: true,
38
            pause: true
39
        });            
40
    },
41
    
42
    prepareTabs: function(i, slide) {
43
        // return markup from hardcoded tabs for use as jQuery cycle tabs

44
        // (attaches necessary jQuery cycle events to tabs)

45
        return $slideshow.tabs.eq(i);
46
    },
47
48
    activateTab: function(currentSlide, nextSlide) {
49
        // get the active tab

50
        var activeTab = $('a[href="#' + nextSlide.id + '"]', $slideshow.context);
51
        
52
        // if there is an active tab

53
        if(activeTab.length) {
54
            // remove active styling from all other tabs

55
            $slideshow.tabs.removeClass('on');
56
            
57
            // add active styling to active button

58
            activeTab.parent().addClass('on');
59
        }            
60
    }            
61
};
62
63
64
$(function() {
65
    // initialise the slideshow when the DOM is ready

66
    $slideshow.init();
67
});


NOTE: To keep this tutorial short, I won't explain everything
in this new javascript file but if you have any questions, feel free
to ask in the comments below and I'll do my best help you out =)

Open your updated slideshow in a browser (ensuring there is no #slide-{num}) on
the end of your URL) and wait… See it sliding?…
Great! Now you can click the tabs and watch it slide a little quicker.


Step 5: Highlighting the active tab

So, we've got it working but what's this $slideshow.activateTab()
method that we added? Well it isn't entirely necessary since the jQuery Cycle
plugin already adds an .activeSlide class to the active navigation
link for you, however, I like to give a little more control over my navigations so
this method just adds an .on class to the parent <li>
of the active link.

With this in place, you can add the following CSS to the end of our
slideshow.css stylesheet to highlight the active tab:

1
2
#slideshow .slides-nav li.on,
3
#slideshow .slides-nav li.on a {
4
background-color: #eee;}
5
6
#slideshow .slides-nav li.on a {
7
position: relative;
8
top: -4px;}

When you preview, you'll probably notice that the first tab isn't highlighted on
page load…this is easy to fix…just use jQuery to add a .js
class to the <body> tag as shown below:

1
2
$(function() {
3
    // add a 'js' class to the body
4
    $('body').addClass('js');
5
    
6
    // initialise the slideshow when the DOM is ready
7
    $slideshow.init();
8
});

Then prepend the CSS we just added with the new .js class:

1
2
.js #slideshow .slides-nav li.on,
3
.js #slideshow .slides-nav li.on a {
4
background-color: #eee;}
5
6
.js #slideshow .slides-nav li.on a {
7
position: relative;
8
top: -4px;}

This means the highlighted buttons will only be styled if the user has javascript
enabled and then we hard code the .on class for the first tab in
the slideshow navigation:

1
2
<ul class="slides-nav">
3
    <li class="on"><a href="#slide-one">Slide one</a></li>
4
    <li><a href="#slide-two">Slide two</a></li>
5
    <li><a href="#slide-three">Slide three</a></li>
6
</ul>

…and voila! Try disabling/enabling JavaScript and refreshing the
slideshow to make sure everything still works and we're done!

Javascript OffJavascript OffJavascript Off
Final ProductFinal ProductFinal Product


Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.