JS Cycle

by TheFiddler

HTML

<div id="cycler1" class="cycle">
    <img data-imgid="1" class="active" src="http://placehold.it/100x100" alt="" />
    <img data-imgid="2" src="http://www.insertpuppy.com/100-100" alt="" />
</div>
<div style="clear:both"></div>
<div id="cycler2" class="cycle" style="margin:150px 0 0 0;">
    <img data-imgid="1" class="active" src="http://www.insertpuppy.com/100-100" alt="" />
    <img data-imgid="2" src="http://placehold.it/100x100" alt="" />
</div>

CSS

#cycler1, #cycler2 {
    position:relative;
}
#cycler1 img, #cycler2 img {
    position:absolute;
    z-index:1
}
#cycle1r img.active, #cycle2r img.active {
    z-index:3
}

JavaScript

var stopAnim = false;

var idx = 0;
var stopped;
var whichcycler = "#cycler2"
$('div.cycle img').click(function () {
    if (!stopAnim) {
        stopAnim = true;
        stopped = idx;

    } else {
        var $active = $(whichcycler + ' .active');
        var $next = ($active.next().length > 0) ? $active.next() : $(whichcycler + ' img:first');
        $next.css('z-index', 2);
        $active.fadeOut(500, function () {
            $active.css('z-index', 1).show().removeClass('active');
            $next.css('z-index', 3).addClass('active');

        });
    }
});

function doReplay() {

    if (!stopAnim) {

        var $active = $(whichcycler + ' .active');
        var $next = ($active.next().length > 0) ? $active.next() : $(whichcycler + ' img:first');
        $next.css('z-index', 2);
        $active.delay(2000).fadeOut(1500, function () {
            $active.css('z-index', 1).show().removeClass('active');
            $next.css('z-index', 3).addClass('active');
            doReplay();
        });

    } else {
        $("div#" + stopped).show();
        return false;
    }
}
doReplay();