Simple Jquery Slide Show with Next Prev Button

http://blog.kangrian.com

by Ayyappan Sakthivadivel

HTML

<div class="slideshow">    
    <div class="inner">Test1</div>
    <div class="inner">Test2</div>
    <div class="inner">Test3</div>
    <div class="inner">Test4</div>
    <div class="inner">Test5</div>    
</div>
<button id="prev">Prev</button>
<button id="next">Next</button>

CSS

.slideshow {
    position: relative;
    /* necessary to absolutely position the images inside */
    width: 500px;
    /* same as the images inside */
    height: 100px;
}
.slideshow img {
    position: absolute;
    display: none;
}
.slideshow img:first-child {
    display: block;
    /* overrides the previous style */
}

JavaScript

var interval = undefined;
$(document).ready(function () {
    interval = setInterval(getNext, 2000); // milliseconds
    $('#next').on('click', getNext);
    $('#prev').on('click', getPrev);
});

function getNext() {
    var $curr = $('.slideshow .inner:visible'),
        $next = ($curr.next().length) ? $curr.next() : $('.slideshow .inner').first();

    transition($curr, $next);
}

function getPrev() {
    var $curr = $('.slideshow .inner:visible'),
        $next = ($curr.prev().length) ? $curr.prev() : $('.slideshow .inner').last();
    transition($curr, $next);
}

function transition($curr, $next) {
    clearInterval(interval);

    $next.css('z-index', 2).fadeIn('slow', function () {
        $curr.hide().css('z-index', 0);
        $next.css('z-index', 1);
    });

}