Creating a simple Slider with JavaScript

In diesem Tutorial wird beschrieben, wie man einen einfachen Image Slider umsetzen kann und diesen per jQuery steuert.
Der Text ist auf Englisch verfasst.

Introduction

Creating a simple slider with javascript/jquery is easier as you may think. I know there a hundrets or even thousands of plugins out there which will give you a ready made slider that you just copy and paste into your project and change some settings to fit your needs. But sometimes it is necessary to implement a simple slider for a certain project by hand without any use of an external plugin. I for my self also like it to have full control over the code i write. I created my slider by myself and I always know exactly what it can do and what not. Depending on the situation I can add more features or change anything in the code. The goal of this tutorial is to have a basic slider that simply do its work – sliding. Without any extra css fading or other stuff. It just shall slide and that’s it.

See it in action 

view github repository

Features

  • Simple slider with sliding from right to left
  • Autoslide function
  • Automatic resetting of the slider after one period

Getting started

The simple slider is based on jQuery. As I’m going to use very basic jQuery functionality it should be possible that it is working with all common jQuery 1.x versions.

The HTML

The HTML setup is simple. We use an unordered list with an ID and add some images into it. You can add some links as well so your visitors can click on the images. You also can add other media stuff here, like text or videos, it is up to you. The list is surrounded by a container which must have a fixed width and some CSS properties.

<div id="slider-container">
 <ul id="slider-list">
  <li><a href="#"><img src="img/01.jpg" /></a></li>
  <li><a href="#"><img src="img/02.jpg" /></a></li>
  <li><a href="#"><img src="img/03.jpg" /></a></li>
  <li><a href="#"><img src="img/04.jpg" /></a></li>
  <li><a href="#"><img src="img/05.jpg" /></a></li>
  <li><a href="#"><img src="img/06.jpg" /></a></li>
 </ul>
</div>

The CSS

The CSS does the following: The slider container is given a fixed size and overflow hidden property, so we will see only one list item at once and not the whole list. The slider list has a very large width. The container works basically as a mask layer showing only a fixed part of the slider list. The list items float left so they are arranged next to each other. In this example we use images with different dimensions. We need to take care for this by defining the list item dimensions. We also give each list item the same dimensions like the slider container and add overflow hidden. This will hide parts of images that are larger.  The image which is inside the list item gets a height of 480px and the width is calculated depending on the ratio by the browser. So with that we are able to add images with different dimensions.

We also add some basic hover effect to the two buttons by using CSS3 transitions and opacity. This can be changed of course.

#slider-container {
 width: 640px;
 height: 480px;
 margin: 0 auto;
 padding: 0;
 overflow: hidden;
 position: relative;
 }

ul#slider-list {
 width: 2000em;
 height: 480px;
 padding: 0;
 position: relative;
 }
ul#slider-list li {
 width: 640px;
 height: 480px;
 display: block;
 float: left;
 text-align: center;
 overflow: hidden;
 }
ul#slider-list li img {
 width: auto;
 height: 480px;
 }

a#slider-prev-btn,
a#slider-next-btn {
 width: 40px;
 height: 60px;
 margin: -30px 0 0 0;
 color: #444;
 font-size: 4em;
 line-height: 50px;
 text-align: center;
 text-decoration: none;
 position: absolute;
 left: -22px;
 top: 50%;
 z-index: 99;

 -webkit-opacity: 0.75;
 -moz-opacity: 0.75;
 opacity: 0.75;

 -webkit-transition: all 80ms ease-in-out;
 -moz-transition: all 80ms ease-in-out;
 transition: all 80ms ease-in-out;
 }
a#slider-next-btn {
 left: auto;
 right: -22px;
 }
a#slider-prev-btn:hover,
a#slider-next-btn:hover {
 -webkit-opacity: 1.0;
 -moz-opacity: 1.0;
 opacity: 1.0;
 }

The JavaScript

In order to keep our code understandable I will use an object based definition. We define an object in which we store all our settings and parameters used for the slider. So while we program the slider functions later we basically just change the status variables inside of this object.

var imageSliderObj = {

 // the width of our slider (items should have this value too)
 width: 960,

 // the speed of the slider auto sliding (ms)
 speed: 8000,

 // the speed our animation should run (ms)
 transitionSpeed: 250,

 // the jQuery object of the slider list
 el: $('ul#slider-list'),

 // the length of the slider
 length: $('ul#slider-list').children().length,

 // the current position of the slider: default 0
 current: 0,

 // the interval variable to store from setInterval()
 interval: null,

 // this will store the function for the auto sliding
 autoSlideFunction: null
};

Once we have defined our settings object we can start implementing the slider features. First we will add a previous nad next button to control the slider. The Buttons will react on mouse click. To achieve that we use the built-in jQuery click event which we will add to the two buttons. This event will be fired once the user moves the mouse over the elemnt and presses the mouse button. The event basically works for mobile devices as well (eg. IPad, Android).

The only difference of a previous and next button is the direction our slider should move. We will use jQuery’s animate() function the move the slider smoothly. The slider will be moved to the left always that’s why there is a – (minus) in front of the value and we are not moving each list element on its own we just move the entire list (<ul>). Therefore the list must have set the css property <position: relative> (also <position: absolute> should work).

You also can create an own function for the slider moving an call it from wherever you want. This could be usefull if you want to add a thumbnail pagination for your slider, but for this tutorial I want to use it as it is because I want to prevent using too many functions here.

$(document).ready(function($){

 $('#slider-next-btn').click(function(e){

  // prevent default click behaviour (remove it if you don't use a  link)
  e.preventDefault();

  // remove the autosliding as it could interrupt the cliding on click
  clearInterval(imageSliderObj.interval);

  // increment the current position our slider is at
  imageSliderObj.current++;

  // if the slider reaches the last item reset it to 0
  if(imageSliderObj.current == (imageSliderObj.length))
   imageSliderObj.current = 0;

   // move the slider smoothly
   imageSliderObj.el.stop().animate({'left': -(imageSliderObj.current * imageSliderObj.width)}, imageSliderObj.transitionSpeed);

   // add the auto sliding back to the slider
   imageSliderObj.interval = setInterval(imageSliderObj.autoSlideFunction, imageSliderObj.speed);
 });

});

The event function for the previous button work quite similar than the next button. The only two differences are that we need to decrement the <imageSliderObj.current> variable instead of increment it. The other thing is the if condition. Here we need to check if our slider reaches the first item (0) and then reset the slider to the last item.

$('#slider-prev-btn').click(function(e){

...

 if(imageSliderObj.current == 0)
  imageSliderObj.current = imageSliderObj.length-1;
 else
  imageSliderObj.current--;

...

});

Adding the auto slide function.

The auto slide function is a nice feature and our slider should not miss it. We want our slider auto advancing depending on a given time we have defined in our slider object before. We will us the JavaScript function setInterval() which will do the trick here. Simply call the auto slide function with the setInterval() function and give it a speed. The auto slide function basically works similar to the next-button event function.


imageSliderObj.autoSlideFunction = function(){

 // increment the slider on every tick
 imageSliderObj.current++;

 // check if  the slider reaches the end and reset it
 if(imageSliderObj.current == (imageSliderObj.length))
  imageSliderObj.current = 0;

 // move the slider
 imageSliderObj.el.stop().animate({'left': - (imageSliderObj.current * imageSliderObj.width)}, imageSliderObj.transitionSpeed);

};

// set the inter val function and add it to our slider object so we can call it later
imageSliderObj.interval = setInterval(imageSliderObj.autoSlideFunction, imageSliderObj.speed);

Now our image slider is complete for now. All important settings have been made and we can put all the code together. On the example page I added everything into the index.html file. Feel free split things up into seperate files. See the source code there to see how to pack the things together.

Example page 

Further reading

I think there are a thousand ways to create an image slider like this. It is just a basic example here. I hope you enjoyed reading it. If any questions are left please add a comment.

// thanks

Kommentare (1)

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.