In this post I'll show you how to create a jQuery automatic content slider plugin from scratch. Is it difficult? Absolutely not! All the work is done by simply calculations of widths and heights and by an internal JavaScript timer. Let's see how we can fulfill this task. First of all, let's start with our basic markup:
<div id="slider"> <div class="slide">...</div> <!--more slides--> </div>
All we have to do is to add a CSS class named slide
to our slides and then let our plugin to do its work. Here's its code:
(function($) { $.fn.slider = function(options) { var that = this; var defaults = { sliderWidth: 500, sliderHeight: 400, centered: false, speed: 1000 }; options = $.extend(defaults, options); that.css({ width: options.sliderWidth, height: options.sliderHeight, position: 'relative', overflow: 'hidden' }); if(options.centered) { that.css({marginLeft: 'auto', marginRight: 'auto'}); } var slides = that.find('div.slide'); var slideLength = slides.length; slides.css({ width: options.sliderWidth, height: options.sliderHeight, 'float': 'left' }); slides.wrapAll('<div id="slider-wrapper"></div>'); that.find('#slider-wrapper'). css({ position: 'relative', height: options.sliderHeight, width: options.sliderWidth * slideLength }); var getPositions = function() { var positions = []; slides.each(function(i) { var left = $(this).position().left; positions[i] = left; }); return positions; }; return that.each(function() { var offsets = getPositions(); var index = 0; var sliderWrapper = that.find('#slider-wrapper'); var interval = setInterval(function() { index++; if(index == slideLength) { index = 0; } sliderWrapper.animate({ left: - offsets[index] }, options.speed); }, options.speed); }); }; })(jQuery);
First, we set a reference to our target element in a variable called that
. Then we create our plugin options, which include:
- the width of the slider
- the height of the slider
- whether the slider must be centered or not
- the speed of the animation.
Then we set several CSS styles to the slider container, including its width, height, overflow and positioning. All these styles are required by the plugin to work. Then we set other styles to each slide, thus making them wide and tall as their container, plus left-floated. But wait, we actually need a container to create the sliding effect, so we create one that wraps the entire slide set. Then we create our sliding effect as in many other sliders, that is, using a counter and a timer. You can see the demo below.