Web Foundations
Article

How to Make a Simple Image Slider With HTML, CSS and jQuery

By Tim Evko

Slideshows, image sliders, magic picture changing boxes: whatever you call them, the pattern is used all over the internet, so much so that nearly every website has one. If you’re a web developer, the time will come when you may have to build one on your own. With that in mind, let’s look at how we can build a simple image slider using HTML, CSS, and jQuery.

The HTML

We’ll start off by creating a container element, which has the class container. Inside of that lie our images. The images are wrapped with div tags, so the slides can be turned into links, or content other than images can be used as a slide. The first container div has some inline style that makes sure the first image in the slider will be visible on page load. There are also two button elements which are used to manually cycle through slides at the users request.

The CSS

This is where we set the width of the image slider, container divs, and the images inside of them. It’s important to note that all of our container divs are set to display: none;. If they weren’t, all of our images would be visible at the same time. We’ll use JavaScript to set a container div to display: inline-block;, while the rest remain hidden.

The JavaScript

First up, we need to define a few important variables. The first variable is currentIndex, and it is set to 0. The second variable is items, which is set to $('.container div'). This will return a list of container divs with images inside of them. The third variable is itemAmt, which is set to the length of our items variable. This last variable gives us the total amount of slides in our image slider.

Next, we create a function called ‘cycleItems’. This function will be used to display the correct image, while ensuring that the others stay hidden. Inside of this function, we create a variable called item. This variable is set to $('.container div').eq(currentIndex). The eq method provided by jQuery takes an integer, and will target the first item returned by $('.container div') that matches the integer. So if currentIndex is 0, $('.container div').eq(currentIndex) will target the first image container in our image slider. The next thing to do inside of our cycleItems function is to hide all of our image container divs, and set item to display: inline-block;.

To make sure that our images rotate automatically, we need to provide a way to continuously call our cycleItems function after a certain amount of time has passed. We do this by creating another variable called autoSlide. This variable stores a setInterval function, which takes a 3000 millisecond delay, or three seconds. Inside of that function, we increment the currentIndex variable by one, so that $('.container div').eq(currentIndex) will always reference the next container div. Then we define a very important ‘if’ statement. This statement says that if our currentIndex variable is greater than the total amount of images in our slider, reset the variable back to zero. If we didn’t have this if statement, we wouldn’t be able to cycle through our list of images. After the if statement, we call our cycleItems function.

Next we define our previous and next actions. These define what will happen when we click the previous and next buttons. They work like the autoSlide function, except they cancel the automatic cycling when clicked. To manually cycle through the slides, clicking the next button adds one to the currentIndex variable, while clicking the previous button subtracts one from the currentIndex variable.

The Demo

See the Pen JS pen #1 by SitePoint (@SitePoint) on CodePen.

Bonus

To see an image slider built using only CSS and HTML, check out this demo by Zack Wallace!

  • Ramy El-Mahdy

    I tried the codes and it doesn’t work with me, any help??

    • July Mariana

      Try to call the Jquery to your page! If it doesn’t work, copy the ‘page source’ of the frame!

  • Bianca

    I tried it and it works superb, many thanks!

  • Mark

    i TRY ALL THE CODES IT DOESNT WORK :3

    I try the HTML CODE but its not IMAGE SLIDER

  • Victor Martin

    thank you very much!! this code is so simple that i can’t believe it

  • pamfromoz

    I copied the code, tweaked the image links and it doesn’t work. What did others tweak to get this to work? Thanks!

  • Blazing saddles

    Is this in html5?

  • rajat

    I tried it but it didnot work. all the images showed on html page on staring

  • Tim

    Just a note….you have to have the JS after the slide show to make it work. Figured this out after a while. I had the script in the head tag and it wasn’t working! Put the script right before the ending body tag and now it works fine. Hope this helps!

    • Sluimerstand

      You can also wrap the JS in this code: $(document).ready(function() { [code here] });
      Then it waits for the page to fully load until it initializes the code. :)

    • Dave

      Thanks you are right! Ending Body it works better i think

    • mandeep maharjan

      thanks a lot man now the slider works fine … :D

    • Friendly Neighborhood Develope

      Javascript files should always be called before the closing body tag, its just good practice.

  • Chintan

    Steps:
    1. Need to include “jquery.min.js” before tag
    2. Need to change JS file, replace first three line with below code.
    var currentIndex = 0;
    var items = $(‘.container div’);
    var itemAmt = items.length;

    Enjoy !!!

    • Thank you! Most comprehensive answer here.

  • jagdeep singh

    can i take slider in left side now its in center

  • jagdeep

    i want this code full and how can i change image and select my photos and link of website location please

  • Ayman

    Great slider. I wonder how to make the slider to autoslide again after clicking the next/prev buttons?

    • Newbie Coder

      Hi Ayman

      See the last response below.
      I have modified the code to perform the task you so desire.
      Enjoy! :)

    • Newbie Coder

      Sorry meant to say below in isha’s comment.

  • isha

    code is working good for me, but i was wanting if the button is clicked after some time again the time interval get started.

    • Newbie Coder

      just remove the “clearInterval(autoSlide);” line if you want it to continue sliding after the button clicks.
      If you want to wait a certain period before it continues sliding, just create a timer and add it after the “cycleItems();”.
      Or alternatively, you can google if jQuery has a resetInterval, or restartInterval etc etc.

    • Newbie Coder
    • Newbie Coder

      Hey isha,
      Took the liberty to re-write the js code for you.
      When you click the navigation buttons it will cycle the new image and restart the autoSlide function I have created.
      Just replace your javascript code with the following code:

      $(document).ready(function(){
      var currentIndex = 0,
      items = $(‘.container div’),
      itemAmt = items.length;
      var autoSlide;

      slide();

      function cycleItems(){
      var item = $(‘.container div’).eq(currentIndex);
      items.hide();
      item.css(‘display’, ‘inline-block’);
      }

      function slide() {
      autoSlide = setInterval(function () {
      currentIndex += 1;
      if (currentIndex > itemAmt – 1) {
      currentIndex = 0;
      }
      cycleItems();
      }, 3000);
      }

      $(‘.next’).click(function () {
      currentIndex = currentIndex + 1;
      if (currentIndex > itemAmt – 1) {
      currentIndex = 0;
      }
      cycleItems();
      slide();
      });

      $(‘.prev’).click(function () {
      clearInterval(autoSlide);
      currentIndex = currentIndex – 1;
      if (currentIndex < 0) {
      currentIndex = itemAmt – 1;
      }
      cycleItems();
      slide();
      });
      })

      • mohamed

        hii Newbie Coder

        i tried to add fade-in fade-out Effect to create slideshow in HTML and i cant add Previous and Next buttons

        please help with my code

        #myslider {

        opacity:1;

        filter: alpha(opacity=100);

        transition: opacity 1s;

        }

        #myslider.fadeOut {

        opacity:0;

        filter: alpha(opacity=0);

        }

        window.onload=function()

        {

        var ListImages =

        [

        ‘images/s01.jpg’,

        ‘images/s02.jpg’,

        ‘images/s03.jpg’,

        ‘images/s04.jpg’,

        ],

        startimage = 0;

        Duration = 6900;

        function slideShow() {

        document.getElementById(‘myslider’).className += “fadeOut”;

        setTimeout(function()

        {

        document.getElementById(‘myslider’).src = ListImages[startimage];

        document.getElementById(‘myslider’).className = “”;

        },2000);

        startimage=startimage + 1;

        if (startimage == ListImages.length)

        {

        startimage = 0;

        }

        setTimeout(slideShow,Duration);

        }

        slideShow();

        }

        please help me

      • Shohan Sakib

        I tried this slider. It worked fine. But after clicking .next or .prev, the slider doesn’t run at it’s actual speed but it runs faster. How can I make it run at it’s actual speed even after clicking the .next and .prev. Thank you.

  • Lizz

    If the slider doesnt work add the following code around the jquery code:

    $(function(){
    PASTE JQUERY CODE FROM ABOVE RIGHT HERE…
    });

    Thank me later. Flies away.
    Also thanks for the slider tips from the maker! :)

    • nitesh

      Thanks for your sharing

    • Barb

      Thank you for saving me hours of work!!

  • Siva Kanagaraj

    Works fine thanks for d code :)

    Place d JS code before

    Called jquery.min.js inside

    replace first 3 line of JS
    var currentIndex = 0;
    var items = $(‘.container div’);
    var itemAmt = items.length;

  • Mary

    Is there a way to create buttons for every image?

  • MM Fahim

    I tried all of these codes and it doesn’t work with me, any help??

  • daniel estabillo

    Can’t get it to work, I made an external javascript file “JS.js” called inside tag. Not working, Please help. Thanks

    • lualps

      The code is executed sequentially, load the script after the html of the slider is loaded

  • King Disqus

    How can i use this slider twice in one page ?

  • Suman

    Its Very Nice .. working properly. Thanks for such a good slider code dear maker :) :)

  • Jila

    Hello! I tried this code and it works, but Can I ask you a questionS please?
    I create the similar structure in HTML but I use the ul and li to my slides. I think your explanation is good, but I didn’t understood very well when you said “The third variable is itemAmt, which is set to the length of our items variable. This last variable gives us the total amount of slides in our image slider.”. In my opinion this last variable gives us the amount of one slide, but not the total amount of slides. Do no not hesitate to correct me, if I am wrong. I’m trying to understand jquery and for me it’s very difficult.
    I have another things to ask you, Can you explain me better why you use the if statement, please?
    And, last question, Every images has a different texts, when I click the button, also the image must be change, How can I do to add this ? I added to every image a data with my text but I don’t have any idea to do this action.
    Thank you so much !

  • Koford

    How do i remove cycle, i only want clicking.

  • var slideimages = new Array() // create new array to preload images

    slideimages[0] = new Image() // create new instance of image object

    slideimages[0].src = “first_image.gif” // set image src property to image path, preloading image in the process

    slideimages[1] = new Image()

    slideimages[1].src = “second_image.gif”

    slideimages[2] = new Image()

    slideimages[2].src = “third_image.gif”

    //variable that will increment through the images

    var step=0

    function slideit(){

    //if browser does not support the image object, exit.

    if (!document.images)

    return

    document.getElementById(‘slide’).src = slideimages[step].src

    if (step<2)

    step++

    else

    step=0

    //call function "slideit()" every 2.5 seconds

    setTimeout("slideit()",2500)

    }

    slideit()

    I am student of BMIT college. if you want to more information regarding same than please contact us by
    email address is webteam@bmitjaipur.org

  • happy

    great tutorial thanks for this i found another good tutorial of how to create you own image slider using jquery and css http://talkerscode.com/webtricks/basic-image-slideshow-with-previous-and-next-button-using-jquery.php

  • Jeff Bain

    I copy and pasted all the code exact and I get the page to show buttons and proper showing of the first image but no slider and buttons don’t work. Does anybody know what could be wrong?

    • Shweta Saha

      Add jquery.min to your page..It will work

  • mohamed

    whats wrong with this code

    #myslider {

    opacity:1;

    filter: alpha(opacity=100); /* For IE8 and earlier */

    transition: opacity 1s; /* Image become more bright for about 1s, smooth transition*/

    }

    #myslider.fadeOut {

    opacity:0; /* image is Transparent */

    filter: alpha(opacity=0); /* For IE8 and earlier */

    }

    #container .prevButton{

    height:72px;

    width:68px;

    position:absolute;

    background:url(‘images/buttons.png’) no-repeat;

    top:50%;

    margin-top:-36px;

    cursor:pointer;

    z-index:2000;

    background-position:left top;

    left:0

    }

    #container .prevButton:hover{

    background-position:left bottom;left:0;}

    #container .nextButton{

    height:72px;

    width:68px;

    position:absolute;

    background:url(‘images/buttons.png’) no-repeat;

    top:50%;

    margin-top:-36px;

    cursor:pointer;

    z-index:2000;

    background-position:right top;

    right:0

    }

    #container .nextButton:hover{

    background-position:right bottom;right:0;}

    window.onload=function()

    {

    var ListImages =

    [ /* Change images if downloaded from below */

    ‘images/s01.jpg’, /* Change here: to day.jpg */

    ‘images/s02.jpg’, /* Change here: to monday.jpg */

    ‘images/s03.jpg’, /* Change here: to tuesday.jpg */

    ‘images/s04.jpg’,

    ],

    startimage = 0;

    Duration = 6900;

    function slideShow() {

    document.getElementById(‘myslider’).className += “fadeOut”;

    setTimeout(function()

    {

    document.getElementById(‘myslider’).src = ListImages[startimage];

    document.getElementById(‘myslider’).className = “”;

    },2000);

    startimage=startimage + 1;

    if (startimage == ListImages.length)

    {

    startimage = 0;

    }

    setTimeout(slideShow,Duration);

    }

    slideShow();

    };

    function getNext() {

    var $curr = $(‘.slideshow img:visible’),

    $next = ($curr.next().length) ? $curr.next() : $(‘.slideshow img’).first();

    transition($curr, $next);

    }

    function getPrev() {

    var $curr = $(‘.slideshow img:visible’),

    $next = ($curr.prev().length) ? $curr.prev() : $(‘.slideshow img’).last();

    transition($curr, $next);

    }

    function transition($curr, $next) {

    clearInterval(interval);

    $next.css(‘z-index’, 2).fadeIn(‘slow’, function () {

    $curr.hide().css(‘z-index’, 0);

    $next.css(‘z-index’, 1);

    });

    }

  • Dragos Rizescu

    Excellent post! Thank you very much!

  • William Johnson

    I was wondering, how to add some text to the right side, so quarry can swipe image with tet?

    • William Johnson

      I got it, just applied some styles

  • Ariyo Usman Oluwafemi

    check out this demo by Zack Wallace! I copy and use the code on this link.It works fine but I dont know where to add the image because when I remove the link image on there and I put mine,It display the image but does not display the rest image,it seems I dont know where or how to add the rest image on it.Pls quickly assist me with these problem.

  • Efrain Camacho

    How do you put these codes together?

  • Hey there!

    Thanks For sharing Tim! I used Zack Wallace’s example on my website and worked flawlessly.
    My only concern is how to make it fully responsive for any device.. any clue?

    Thanks!
    Gaston

  • Dean

    I tried it but only the first image is showing, I even voted the codes and paste but it’s not sliding and the next/prev buttons aren’t working.
    Pls I need help. Many thanx

  • Imane E.

    Thank you for this article, did it just with your very exact explanation.

  • d a

    Hey this code is great, I really want to add a fade in function though as it cycles. Any help?

  • saad

    its simply awesome ! thankyou

  • Toral Shah

    Done my code is working but tat isnt responsive….need your help

  • Toral Shah

    done code is working…. but tat isnt responsive…need help!

  • SLN AGENCIES

    hi

  • BoneStarr

    Hi, great slider, I got this working perfectly, but I wanted to know how you have multiple sliders one page? currently the slider thinks that the two sliders are one?

  • Usama Naseer

    how to set transition speed so when u click previous or next there will be some speed to which they move ?

  • Velja Topolovački

    Amazing plugin. Works like a charm. :D

  • Melissa

    Could you build a image slider with in a image slider?