Click here to Skip to main content
15,879,474 members
Articles / Web Development / HTML5
Tip/Trick

JQuery Image Slider Tutorial for Beginners

Rate me:
Please Sign up or sign in to vote.
4.77/5 (8 votes)
3 Jan 2015CPOL2 min read 91.1K   2.6K   10   14
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)


Written By
Software Developer
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questiongallery Pin
Member 1449504812-Jun-19 6:08
Member 1449504812-Jun-19 6:08 
QuestionPretty Good Pin
Member 1335828012-Aug-17 3:49
Member 1335828012-Aug-17 3:49 
AnswerRe: Pretty Good Pin
Dilan Shaminda24-Sep-17 23:10
professionalDilan Shaminda24-Sep-17 23:10 
QuestionHow to store last seen image of an image slider in session state in ASP.NET MVC Pin
Atanu Ghosh18-Jun-15 20:11
Atanu Ghosh18-Jun-15 20:11 
GeneralNicely done. Pin
Dennis Cani2-Feb-15 0:15
Dennis Cani2-Feb-15 0:15 
GeneralRe: Nicely done. Pin
Dilan Shaminda2-Feb-15 5:45
professionalDilan Shaminda2-Feb-15 5:45 
Questiondemo Pin
Member 113482996-Jan-15 14:46
Member 113482996-Jan-15 14:46 
AnswerRe: demo Pin
Dilan Shaminda6-Jan-15 16:42
professionalDilan Shaminda6-Jan-15 16:42 
QuestionImages Pin
alfred20125-Jan-15 9:23
alfred20125-Jan-15 9:23 
AnswerRe: Images Pin
Dilan Shaminda5-Jan-15 16:55
professionalDilan Shaminda5-Jan-15 16:55 
GeneralMy vote of 5 Pin
Carsten V2.05-Jan-15 4:36
Carsten V2.05-Jan-15 4:36 
GeneralRe: My vote of 5 Pin
Dilan Shaminda5-Jan-15 4:43
professionalDilan Shaminda5-Jan-15 4:43 
QuestionExcellent!!! Pin
Poojanath, CSPO4-Jan-15 17:30
Poojanath, CSPO4-Jan-15 17:30 
AnswerRe: Excellent!!! Pin
Dilan Shaminda4-Jan-15 19:20
professionalDilan Shaminda4-Jan-15 19:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.