How To Make A Slider

Looking for a jQuery slider plugin? Think again. Anyone with decent HTML, CSS and JavaScript knowledge can build a slider with just a small amount of code.

Below is what you need to obtain the basic functionality of a slider, that is, a series of horizontally sliding images (or anything else) controlled by JavaScript.

HTML

<div class="slider">
  <ul>
    <li><img src="img/1.png"></li>
    <li><img src="img/2.png"></li>
    <li><img src="img/3.png"></li>
    <li><img src="img/4.png"></li>
  </ul>
</div>

We need three things to build a slider in its simplest form…

CSS

.slider {
  width: 400px; height: 300px;
  overflow: hidden;
}
  .slider > ul {
    /* styled by JS to match the added width and height of all <li>’s */
    position: relative;
    left: 0;
    -webkit-transition: 0.5s left;
    -moz-transition: 0.5s left;
    -ms-transition: 0.5s left;
    -o-transition: 0.5s left;

    list-style: none;
    margin: 0; padding: 0;
  }
    .slider > ul > li {
      float: left;
      width: 400px; height: 300px;
    }

Notice the following properties…

JavaScript

  var Slider = function() { this.initialize.apply(this, arguments) }
  Slider.prototype = {

    initialize: function(slider) {
      this.ul = slider.children[0]
      this.li = this.ul.children

      // make <ul> as large as all <li>’s
      this.ul.style.width = (this.li[0].clientWidth * this.li.length) + 'px'

      this.currentIndex = 0
    },

    goTo: function(index) {
      // filter invalid indices
      if (index < 0 || index > this.li.length - 1)
        return

      // move <ul> left
      this.ul.style.left = '-' + (100 * index) + '%'

      this.currentIndex = index
    },

    goToPrev: function() {
      this.goTo(this.currentIndex - 1)
    },

    goToNext: function() {
      this.goTo(this.currentIndex + 1)
    }
  }

A simple prototype-based class which…

On your page

<script>
  var sliders = []
  $('.slider').each(function() {
    sliders.push(new Slider(this))
  })
</script>

Result

Here’s an HTML page with just the bare stuff you need.