Creating A Simple Image Slider (JQuery Plugin)

Final Result

Before we proceed let's take a look at the final result that we will be producing at the end of this article.


How to produce the end result

Before we dig deep into the implementation, let's see how we can produce the above result.

HTML

The HTML is fairly simple. All we need to do is create a div that would be used to hold the slider.

<div id="slider"></div>
CSS

No explicit css to write. We just need to import a css file containing the styles defined for the slider.

<link rel="stylesheet" type="text/css" href="css/image-slider.css" />
JS

Just few lines of JS code to write. An external js import and a call to JQuery function passing the images as parameters, that would create the slider for us.

<script type="text/javascript" src="js/imgSlider.js" ></script>
<script type="text/javascript"> $(document).ready(function(){ $("#slider").imageSlider({ images:[ 'https://upload.wikimedia.org/wikipedia/commons/4/4b/Glacier3000.PNG', 'https://upload.wikimedia.org/wikipedia/commons/6/67/GrandCombin01.jpg', 'https://upload.wikimedia.org/wikipedia/commons/5/5a/Berner_Alpen.jpg' ] }); }); </script>

Peeking into the External JS (imageSlider.js)

By now it is quite evident that all the code that creates the slider resides in the external js file. Lets get inside it and checkout what's happening in there. Here is what it looks like:

var step=0;
var prev=0;
var timeOut;
var stepMax;
var parentDiv;

jQuery.fn.imageSlider = function(options) {
    parentDiv = this;
    $(parentDiv).addClass("imgSlider");
    $(parentDiv).append("<span id='left-arrow'></span><span id='right-arrow'></span>");

    var dotsWrapper = $("<div class='dots-wrapper'></div>");
    var sliderParent = $('<div id="slider-dots"><div class="dots-container"></div></div>');

    for(var i=0;i<options.images.length;i++)
        $(dotsWrapper).append('<div class="dot" id="dot-'+(i+1)+'"></div>');

    $(sliderParent).append(dotsWrapper);
    $(parentDiv).append(sliderParent);

    for(var i=0;i<options.images.length;i++)
   	$(parentDiv).append('<div class="slider" id="slider-'+(i+1)+'"><img width="960" height="400" src="'+options.images[i]+'" name="slide"></div>');

    stepMax = options.images.length;
    initSlider();
};

function initSlider()
{
    $(parentDiv).mouseenter(function(){
    $("#left-arrow").fadeIn();
    $("#right-arrow").fadeIn();
        $("#slider-dots").fadeIn();
    });
    $(parentDiv).mouseleave(function(){
    $("#left-arrow").fadeOut();
    $("#right-arrow").fadeOut();
	$("#slider-dots").fadeOut();
    });
    $(".dot").click(function(){
	var token = $(this).attr('id').split('-');
	moveToSlide(token[token.length-1]);
    });
    $("#left-arrow").click(function(){
	slideLeftRight('left');
    });
    $("#right-arrow").click(function(){
	slideLeftRight('right');
    });

    $("#slider-"+step).addClass('active');
	step = stepMax;
	slideit();
}

function slideit(){
    prev = step;
	
    if (step<stepMax)
	step++;
    else
	step=1;

    doTransition(step,prev);
	timeOut = setTimeout("slideit()",5000);
}

function moveToSlide(slideNo){
    prev = step;
    step = slideNo;
    doTransition(step, prev);
    clearTimeout(timeOut);
    timeOut = setTimeout("slideit()",5000);
}

function slideLeftRight(direction){
    var show;
    prev = step;
    var hide = prev;
    if(direction=='left'){
	if (step==1){
	    show = stepMax;
	    step = stepMax;
	}
	else{
	    show = step-1;
	    step = step-1;
	}
    }
    else{
	if (step==stepMax){
	    show = 1;
	    step = 1;
	}
	else{
	    show = step+1;
	    step = step+1;
	}
    }
	
    doTransition(show, hide);
    clearTimeout(timeOut);
    timeOut = setTimeout("slideit()",5000);
}

function doTransition(show, hide){
    $("#slider-"+hide).fadeOut("slow");
	$("#dot-"+hide).removeClass('active');
	$("#dot-"+show).addClass('active');
$("#slider-"+show).fadeIn("slow", function(){ $("#slider-"+hide).removeClass('active'); $("#slider-"+show).addClass('active'); }); }

Lets break it into smallers parts and see how its working.

Starting from the top we have some varible declarations.

var step=0;
var prev=0;
var timeOut;
var stepMax;
var parentDiv;

Below are the purpose of each of those:

  • prev and step are used to store the index of the current and previous images. These are helpful when the end user clicks on the previous navigation button, and also aids in the basic sliding function.
  • timeOut is used to keep track of the time for sliding the image.
  • stepMax stores the maximum number of images to slide.
  • parentDiv stores the parent element defined in the html on which the slider is to be loaded.

Next we come accross a jquery plugin function.

The function is responsible for creating html for the image slider is shown below. It accepts the options parameter, that contains the images we have passed as paramters when we called the plugin from our html.

After creating the html, it finally sets the stepMax value and calls the initSlider() method.

jQuery.fn.imageSlider = function(options) {
  parentDiv = this;
  $(parentDiv).addClass("imgSlider");
  $(parentDiv).append("<span id='left-arrow'></span><span id='right-arrow'></span>");

  var dotsWrapper = $("<div class='dots-wrapper'></div>");
  var sliderParent = $('<div id="slider-dots"><div class="dots-container"></div></div>');

  for(var i=0;i<options.images.length;i++)
    $(dotsWrapper).append('<div class="dot" id="dot-'+(i+1)+'"></div>');

    $(sliderParent).append(dotsWrapper);
    $(parentDiv).append(sliderParent);

    for(var i=0;i<options.images.length;i++)
      $(parentDiv).append('<div class="slider" id="slider-'+(i+1)+'"><img width="960" height="400" src="'+options.images[i]+'" name="slide"></div>');

    stepMax = options.images.length;
    initSlider();
};

Below is the html that our plugin generated:

<div class="imgSlider">
  <span id="left-arrow"></span>
  <span id="right-arrow"></span>
  <div id="slider-dots">
    <div class="dots-wrapper">
      <div id="dot-1" class="dot"></div>
      <div id="dot-2" class="dot"></div>
      <div id="dot-3" class="dot"></div>
    </div>
    </div>
    <div id="slider-1" class="slider">
      <img width="960" height="400" name="slide" 
          src="https://upload.wikimedia.org/wikipedia/commons/4/4b/Glacier3000.PNG">
    </div>
    <div id="slider-2" class="slider">
      <img width="960" height="400" name="slide" 
          src="https://upload.wikimedia.org/wikipedia/commons/6/67/GrandCombin01.jpg">
    </div>
    <div id="slider-3" class="slider">
      <img width="960" height="400" name="slide" 
          src="https://upload.wikimedia.org/wikipedia/commons/5/5a/Berner_Alpen.jpg">
    </div>
</div>

Moving ahead we come accross the initSlider() method. The method is pretty much self explanatory. It has all the handling for the navigation arrows and dots. The first two blocks of code are responsible for fading in and fading out of the dots and arrows.

Next the click functions are defined. The click on a dot calls moveToSlide() with a parameter that contains the slide to move to i.e the dot clicked. Similarly, the click on the left/ right arrow calls slideLeftRight() with a paramater 'left'/ 'right' indicating which arrow is clicked.

Finally it makes the current slide as 'active' and calls the slideit() function, which starts the slide show.

function initSlider() {
	$(parentDiv).mouseenter(function(){
		$("#left-arrow").fadeIn();
		$("#right-arrow").fadeIn();
		$("#slider-dots").fadeIn();
	});
	$(parentDiv).mouseleave(function(){
		$("#left-arrow").fadeOut();
		$("#right-arrow").fadeOut();
		$("#slider-dots").fadeOut();
	});
	$(".dot").click(function(){
		var token = $(this).attr('id').split('-');
		moveToSlide(token[token.length-1]);
	});
	$("#left-arrow").click(function(){
			slideLeftRight('left');
	});
	$("#right-arrow").click(function(){
			slideLeftRight('right');
	});

	$("#slider-"+step).addClass('active');
	step = stepMax;
	slideit();
}

The slideit() function, the heart of our image slider, this is where the core resides.

The function is pretty simple to understand. All it does is checks the current slide number(step); if it is less than the maxumim number of images in the slideshow(stepMax), step is increased by one; else its initialized to 1.

Next a function doTransition() is called that adds a bit of fading effect when the image slides.

Finally a timeOut is set i.e. slideit() is called after ever 5 seconds.

function slideit() {
	prev = step;
	
	if (step<stepMax)
		step++;
	else
		step=1;

	doTransition(step,prev);
	timeOut = setTimeout("slideit()",5000);
}

Below is the doTransition() method that adds the fading effect to the image slider while the transition of images takes place.

function doTransition(show, hide)
{
	$("#slider-"+hide).fadeOut("slow");
		$("#dot-"+hide).removeClass('active');
		$("#dot-"+show).addClass('active');
	$("#slider-"+show).fadeIn("slow", function(){
		$("#slider-"+hide).removeClass('active');
		$("#slider-"+show).addClass('active');
	});
}

The moveToSlide() function handles navigation on click of a dot. It recieves a 'slideNo' parameter indicating the slide to move to, which is passed to it from the initSlider() method. It adjusts the prev and step variables, assigning the current slide index to prev and the index to move to the step variable. It then calls the doTransition() for the transition effect.

We also notice that the timer is cleared and reassigned again, this is done so that the transition happens 5 secs after the dot has been clicked i.e. ignore the time since the last transition and start the time tracking again.

function moveToSlide(slideNo) {
	prev = step;
	step = slideNo;
	doTransition(step, prev);
	clearTimeout(timeOut);
	timeOut = setTimeout("slideit()",5000);
}

Finally we have the slideLeftRight() function which handles the navigation through arrows. It recieves a paramter 'direction' indicating the direction to slide.

There's a bit of logic involved here, which might look somewhat clumsy. Let's try to make some sense here. What's happening here is simply identifying the slide to move to, depending on the direction.

Considering the direction is left; if we are on the first slide we need to move to the last slide else move back by one slide. Similarly considering the direction to be right; if we are on the last slide we need to move to the first slide else move forward by one slide. That is what has been accomplished by below piece of code.

Finally it calls the doTransition() and restarts the timer.

function slideLeftRight(direction) {
	var show;
	prev = step;
	var hide = prev;
	if(direction=='left') {
		if (step==1) {
			show = stepMax;
			step = stepMax;
		}
		else {
			show = step-1;
			step = step-1;
		}
	}
	else {
		if (step==stepMax) {
			show = 1;
			step = 1;
		}
		else {
			show = step+1;
			step = step+1;
		}
	}
	
	doTransition(show, hide);
	clearTimeout(timeOut);
	timeOut = setTimeout("slideit()",5000);
}
So that's how we created our simple though useful image slider. Hope you enjoyed the article.
RELATED ARTICLES

Create your own Jquery Plugin

Learn how to create a simple JQuery plugin. This article shows how to create a simple JQuery plugin that can be used to apply different themes to a table.

View Article