Slideshows and carousels can add a lot to your website. They can be used in headers, blog posts, image showcases and more.

Today, we’ll learn how to create your own slideshow from scratch with Javascript and a little HTML.

Getting started

From a pseudocode standpoint, we’ll need to use the following:

  1. Buttons that, when pressed, take the user to the next or previous slide
  2. A collection of items to display
  3. A way to make it such that only one item shows up at a time.
  4. For automatic slideshows, a timer that switches the slide every so often

The first item is easy. JavaScript provides a setInterval(event, time) function, which can trigger events every X milliseconds. The second item could be an <input type="button" onclick="advance()"... /> which changes the item displayed. The third item can be an unordered list, and the fourth will rely on CSS’s display property.

Step 1: Getting our items together

Clearly, we can’t have a slideshow or carousel without text, images, or other media. Let’s display the media in an unordered list as such:

</pre>
<ul style="list-style-type: none; margin-left: -2em;">
	<li id="1" class="hideable" style="display: block;"><!-- YOUR CONTENT HERE --></li>
	<li id="2" class="hideable"><!-- YOUR CONTENT HERE --></li>
	<li id="3" class="hideable"><!-- YOUR CONTENT HERE --></li>
<!-- ... and so on --></ul>
<pre>
<!-- Buttons to go back and forth between slides. --></pre>
<form>
<input type="button" value="Back" />
<input type="button" value="Forward" />
</form>
<pre>

CSS:

.hideable {
    display: none;
}

Notes: For each successive LI, the id increases by 1. On one and only one LI, style="display: block;" must be added as an attribute. This is the list-item that will show up by default when the user loads the slideshow.

Step 2: The JavaScript

Place all your JavaScript within the head tags
Now, we can write the JavaScript that makes the slideshow work. We have three options here: a manual slideshow where users must press buttons to navigate between slides, an automatic slideshow that displays each slide for X milliseconds, or a combination of both (along with a Pause button).

Option 1: Manual navigation

When we made our buttons in Step 1, we specified that they would call a JS Function toggleSlide() when clicked. Now, let’s make that function.

// direction = boolean value: true or false. If true, go to NEXT slide; otherwise go to PREV slide
function toggleSlide(direction) {
    var elements = document.getElementsByClassName("hideable"); // gets all the "slides" in our slideshow
    // Find the LI that's currently displayed
    var visibleID = getVisible(elements);
    elements[visibleID].style.display = "none"; // hide the currently visible LI
    if(!direction) {
        var makeVisible = prev(visibleID, elements.length); // get the previous slide
    } else {
        var makeVisible = next(visibleID, elements.length); // get the next slide
    }
    elements[makeVisible].style.display = "block"; // show the previous or next slide
}
function getVisible(elements) {
    var visibleID = -1;
    for(var i = 0; i < elements.length; i++) {
        if(elements[i].style.display == "block") {
            visibleID = i;
        }
    }
    return visibleID;
}
function prev(num, arrayLength) {
    if(num == 0) return arrayLength-1;
    else return num-1;
}
function next(num, arrayLength) {
    if(num == arrayLength-1) return 0;
    else return num+1;
}

Option 2: Adding a timer for automatic navigation

Instead of making the user click buttons to change slides, we can have a timer to do it automatically.

var interval = 3500; // You can change this value to your desired speed. The value is in milliseconds, so if you want to advance a slide every 5 seconds, set this to 5000.
var switching = setInterval("toggleSlide(true)", interval);

That’s it! Add this to the top of the JavaScript in Option 1.

Option 3: Combining the two

Of course, if you want the slideshow to advance automatically AND have buttons for the user to navigate between slides, you can simply add the code in Option 2 to Option 1, and leave everything else alone.

But what if the user wants to pause?

This is very simple. In the HTML, add the following button between Prev and Next:

<input id="pauseButton" type="button" value="Pause" />

In the JavaScript:

window.paused = false;
function toggleInterval() {
    var button = document.getElementById("pauseButton");
    if(!window.paused) {
        clearInterval(switching);
        button.value = "Resume";
    } else {
        switching = setInterval("toggleSlide(true)", interval);
        button.value = "Pause";
    }
    window.paused = !(window.paused);
}

Extras

First and last buttons

We can add buttons to go to the first or last item in the slideshow.

Add these buttons somewhere in the form:

<input id="firstButton" type="button" value="First" />
<input id="lastButton" type="button" value="Last" />

JavaScript:

// where = boolean. false => go to first item, true => go to last item.
function goToEdge(where) {
    var elements = document.getElementsByClassName("hideable");
    var visibleID = getVisible(elements);
    var firstButton = document.getElementById("firstButton");
    var lastButton = document.getElementById("lastButton");
    elements[visibleID].style.display = "none"; //hides the currently visible item
    if(!where) {
        elements[0].style.display = "block"; //shows the first item
    } else {
        elements[elements.length-1].style.display = "block"; //shows the last item
    }
}

Display current item number

On some slideshows, there is a text hint, like “Slide 2 of 7” or “Page 4”. We can add this to our slideshow.

In the HTML, where you want to display the text, paste this code. I have placed this right above the navigation buttons.

Slide <!-- you can change "Slide" to Page, Item, etc. -->
<span id="slideNumber">
<script type="text/javascript">
var elements = document.getElementsByClassName("hideable");
var vis = getVisible(elements) + 1;
document.write(vis);
</script>
</span>
of <!-- Or use "/", as in Page 3/7 -->
<script type="text/javascript">
// Write the number of slides to HTML. Dynamically changes as you add or remove slides.
document.write(document.getElementsByClassName("hideable").length);
</script>

Now, we need to go into the JS and make some modifications.

On the toggleSlide() function, add this before the final closing bracket:

var sn = document.getElementById("slideNumber");
sn.innerHTML = (makeVisible + 1);

On goToEdge(), modify the if ... else clause as such:

if(!where) {
    elements[0].style.display = "block";
    sn.innerHTML = 1;
} else {
    elements[elements.length-1].style.display = "block";
    sn.innerHTML = elements.length;
}

Demo

You can see a working demo at http://g-liu.github.io/slideshow/. I’ve set the timer to one second per slide to demonstrate better the automatic slide advancing.

The source code can be downloaded on GitHub.

Additional notes

If your slideshow must be created with divs (or similar), you can get rid of the <ul> tags and replace all the <li> with <div> or whatever tag you’re using.

Published by Geoffrey Liu

A software engineer by trade and a classical musician at heart. Currently a software engineer at Groupon getting into iOS mobile development. Recently graduated from the University of Washington, with a degree in Computer Science and a minor in Music. Web development has been my passion for many years. I am also greatly interested in UI/UX design, teaching, cooking, biking, and collecting posters.

10 thoughts on “Tutorial: Basic carousel/slideshow with JavaScript

  1. Thank you for the tutorial, very helpful. How do I make it so that each slide has a front and back and when you click on a button or on the slade it flips to reveal the other side?

  2. I am not able to understand the use of _qevents block of code, Could you explain the same?
    var _qevents = _qevents || [];
    (function() {
    var elem = document.createElement(‘script’);
    elem.src = (document.location.protocol == “https:” ? “https://secure” : “http://edge”) + “.quantserve.com/quant.js”;
    elem.async = true;
    elem.type = “text/javascript”;
    var scpt = document.getElementsByTagName(‘script’)[0];
    scpt.parentNode.insertBefore(elem, scpt);
    })();

    _qevents.push({
    qacct:”p-gxZBSGMCGZ6DU”
    })

      • Hi Geoffrey, may be you know how to add navigation button for changing speed between slides or how to add speed slider in slideshow using Java script.My be you have example of thhese slideshow with speed slider and other navigation buttons.

        Kindly regards, vlado

  3. Thanks for this great tutorial! I do have a couple questions:

    How do you create a button that will call a specific slide?
    How do you attach a custom graphic to that button?
    Is there a way to make the images transition in a slide motion?

    Thanks in advance!

    Best,
    Jeremy

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.