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…
- an overflow container: mask of predetermined width and height (
<div class="slider">
) - a sliding list: child of the container that slides horizontally (
<ul>
) - slides: children of the list that match the container’s dimensions (
<li>
’s)
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…
overflow: hidden
on the<div class="slider">
position: relative
and transitions on the<ul>
(we’ll useleft
for the horizontal sliding)float: left
to arrange<li>
’s horizontally
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…
- has a constructor that receives a
<div class="slider">
- dynamically makes the
<ul>
as large as all<li>
’s - has
.goToPrev()
,.goToNext()
and.goTo(index)
methods, ready to be bound on previous/next links or the usual sequential bullets
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.