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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.