jQuery Image Slider Example

A slider shows one slide at a time. This code has the Next and Previous buttons, and it goes round (after the last slide it shows the first one). Pictures are replaced by text boxes in the test.

HTML

<div id="slider">
  <div class="slide">Slide 1</div>
  <div class="slide" style="display:none">Slide 2</div>
  <div class="slide" style="display:none">Slide 3</div>
</div>
<button id="prev">Previous</button>
<button id="next">Next</button>

CSS

#slider { width: 400px; height: 200px; position: relative; overflow: hidden; }
.slide { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

jQuery code

var $slides = $('#slider .slide');
var current = 0;

function show(index) {
  $slides.eq(current).fadeOut(300);
  current = (index + $slides.length) % $slides.length;
  $slides.eq(current).fadeIn(300);
}

$('#next').on('click', function () { show(current + 1); });
$('#prev').on('click', function () { show(current - 1); });

// automatic change every 4 seconds (stop it with clearInterval)
var timer = setInterval(function () { show(current + 1); }, 4000);

// test
function state() {
  return $slides.map(function () { return $(this).css('display') === 'none' ? '-' : 'VISIBLE'; }).get().join(' ');
}
$('#next').click(); console.log('next:     ' + state());
$('#next').click(); console.log('next:     ' + state());
$('#next').click(); console.log('next:     ' + state() + '  (back to the first)');
$('#prev').click(); console.log('previous: ' + state() + '  (to the last)');
clearInterval(timer);
Console output

next: – VISIBLE –
next: – – VISIBLE
next: VISIBLE – – (back to the first)
previous: – – VISIBLE (to the last)

How it works

  • (index + length) % length makes the numbers go round in both directions.
  • The old slide fades out, and the new one fades in. The slides are placed on top of each other with CSS.
  • setInterval() changes the slide automatically. Stop it when the user clicks, or when the mouse is over the slider, for a better experience.
Note: For a real site also add a pause on hover, touch support and accessible buttons. See Fade and Slide Effects.

Learn more about the similar topics:
Tutorials
jQuery Effects: hide, show and toggle
jQuery Fade and Slide Effects
jQuery animate() Method
jQuery Method Chaining and Callbacks
Exercises & Assignments
Write jQuery code to show and hide a panel with one button
Write jQuery code to make a simple accordion
Write jQuery code to make simple tabs
Interview Questions & Answers
What is method chaining in jQuery?
How do you hide and show an element in jQuery?
How do you use the animate() method in jQuery?
What is a callback function in jQuery and why is it needed in effects?
What is the difference between stop(), finish() and delay() in jQuery?