Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

JQuery Image Slider Tutorial for Beginners

4.77/5 (8 votes)
3 Jan 2015CPOL2 min read 93K   2.6K  
A simple JQuery image slider

Introduction

This is my second post on The Code Project and here I am going to show how to create a simple nice jquery image slider. I hope this tip will help beginners to get an idea about how to create your own simple jquery slider like below:

Slider Preview

Preparing HTML and CSS Markup

Ok, first we will create some HTML code snippet to store our images which are used for the slide show. MainDiv holds the main slider and two navigation images LeftArrow and RightArrow.

HTML
<div id="MainDiv">
   <img src="Images/Image1.jpg" alt="About Us" 
   id="MainImage" width="800" height="600"/>
       <div id="child">
           <img id="Next" src="Images/RightArrow.png" 
           class="img-responsive NextButton"/>
           <img id="Previous" src="Images/LeftArrow.png" 
           class="img-responsive PreButton"/>
       </div>
</div>

CSS for MainDiv

CSS
#MainDiv
{
    position: relative;
    width:800px;
}

#child .NextButton
{
    position: absolute;
    top: 50%;
    right: 2%;
}

#child .PreButton
{
    position: absolute;
    top: 50%;
    left: 2%;
}

Remember it is important to set position of MainDiv to relative. So it positioned element relative to its normal position. Position absolute tells the browser that whatever is going to be positioned should be removed from the normal flow of the document and will be placed in an exact location on the page. Top 50% and right 2% will always display 2% from the right and 50% top of the MainDiv. Read more about CSS positioning here.

Now we are going to set the bottom slider which holds all the images:

HTML
<div id="slider">
   <ul class="slides">
     <li class="slide">
        <img src="Images/Image1.jpg" alt="Image 1" width="200"/>
     </li>
     <li class="slide">
        <img src="Images/Image2.jpg" alt="Image 2" width="200"/>
     </li>
     <li class="slide">
        <img src="Images/Image3.jpg" alt="Image 3" width="200"/>
     </li>
     <li class="slide">
        <img src="Images/Image4.jpg" alt="Image 4" width="200"/>
     </li>
     <li class="slide">
        <img src="Images/Image5.jpg" alt="Image 5" width="200"/>
     </li>      
     <li class="slide">
        <img src="Images/Image6.jpg" alt="Image 6" width="200"/>
     </li>                 
  </ul>
</div>

CSS for Bottom Slider

CSS
#slider
{
    width: 800px;
    overflow: hidden;
    position: relative;
}

    #slider .slides
    {
        display: block;
        width: 8000px;
        margin: 0;
        padding: 0;
    }

    #slider .slide
    {
        float: left;
        list-style-type: none;
        height:120px;
    }

Ok, now we are done with the HTML and CSS part. Let's move on to the jquery part.

First we will get all the images src attribute values to an array for further usage. Here, I used jquery map() and get() functions. You can read further about them here and here.

JavaScript
var tn_array = $(".slides img").map(function () {
        return $(this).attr("src");
    }).get();

$('#MainImage').attr('src', tn_array[0]); // set first image of the list as the MainImage src
$('#Previous').css("visibility", "hidden"); // hide the Previous button at the beginning 

Next Arrow Button Functionality

Some global variables to hold data are as follows:

JavaScript
var lengthImages = tn_array.length; // Length of the image list
var CurrImage = 0; // Keep current Image index
var widthImg = 200; // Width of a image in the list 
var BottomLength = 4; // How many images currently shows in the bottom slide
var IndexDiff;  //This variable is used in the bottom slider click event 
        //as a reference for animate the slider

Next Button Implementation

JavaScript
 $('#Next').click(function () {
    $('#MainImage').fadeOut('slow', function () {
        CurrImage = CurrImage + 1; // Update current image index
        $('#slider .slides').animate({ 'margin-left': '-=' +
        widthImg}, 1000); //animate left margin of the slides list with the value
                //of -widthImg (-200px). So the bottom slider will animate to left side
        $('#MainImage').attr('src', tn_array[CurrImage]); // set next image to Main image
        if (CurrImage == lengthImages - BottomLength) { //This condition is checking
                        //whether the bottom slider has comes to end or not.
            $('#Next').css("visibility", "hidden"); // if true then hide
        }
        if ($('#Previous').css("visibility") ==
                "hidden") { // if Previous button is hidden
            $('#Previous').css("visibility",
                "visible"); //then set it to visible
        }
    }).fadeIn(1000);
});

Previous Button Implementation

$('#Previous').click(function () {
    $('#MainImage').fadeOut('slow', function () {
        CurrImage = CurrImage - 1; // Update the current image index
        $('#slider .slides').animate({ 'margin-left': '+=' + widthImg },
            1000); //animate the bottom slider with += widthImg, it will animate the slider to right
        $('#MainImage').attr('src', tn_array[CurrImage]); // set corresponding image to main image
        if (CurrImage == 0) { // if current slide is the first image
            $('#Previous').css("visibility", "hidden"); // then hide the previous button
        }
        if ($('#Next').css("visibility") == "hidden") { // if next button is hidden
            $('#Next').css("visibility", "visible"); // then set it to visible
        }

    }).fadeIn(1000);
});

Selecting an Image from Bottom Slider

I put the below image to get an idea about what I am going to do. When you select an image from the bottom slider, the selected image will be set as the Main image and then the bottom slider will animate to the left side.

Selected Image

Here is the jquery code segment for animating the bottom slide and setting the selected image for the top slider. I put a comment on every line to explain clearly what happens inside the code.

$('.slides li img').click(function () {
       var Imagesrc = $(this).attr('src'); // get the selected image src
       var ImageIndex = $(this).parent('.slide').index(); // get the selected list item index

       $('#MainImage').fadeOut('slow', function () {
           if (ImageIndex <= lengthImages - BottomLength) { // this condition checks
                   //whether the bottom slider has come to the end or not.
                   //Also this will prevent sliding bottom slider to the left.
               IndexDiff = CurrImage; // Assign Current image index to IndexDiff temporary
               CurrImage = ImageIndex; // Assign selected image index to current image value
               IndexDiff = Math.abs(IndexDiff - CurrImage); // get the difference
               $('#slider .slides').animate({ 'margin-left': '-=' +
                   widthImg * IndexDiff }, 1000); // slide the bottom slider to left by setting
                               //left margin to (widthImg * IndexDiff) pixels.
               $('#MainImage').attr('src', Imagesrc); // set selected image source as main image

               if (ImageIndex != 0) { // image index is not equals to zero
                   if ($('#Previous').css("visibility") == "hidden") { // if previous button is hidden
                       $('#Previous').css("visibility", "visible"); //set it to visible
                   }
               }
               if (ImageIndex == lengthImages - BottomLength) { // check whether the
                               // slider has come to end or not
                   if ($('#Next').css("visibility") == "visible") { // if visible
                       $('#Next').css("visibility", "hidden"); // hide next button
                   }
               }
           }
           else { // if bottom slider has come to end
               $('#MainImage').attr('src', Imagesrc); // set the image source only.
                           // No need to update the image index
           }
           }).fadeIn(1000);
   });

Conclusion

I hope this tip will help beginners to understand how to create their own jquery slider with some simple animation effects. Feel free to ask any questions if you have any. I hope to extend this tip with some more animation effects in future.

Happy programming!

History

  • 01-03-2015: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)