jQuery slideshow

codesolutions

by Joshua Powell

HTML

<header>
    <a href="penis"></a>
    <section id="rotator">
        <ul id="controls"></ul>
        <div id="banners">
            <div id="slide1"></div>
            <div id="slide2"></div>
            <div id="slide3"></div>
            <div id="slide4"></div>
        </div>
    </section>
</header>

CSS

header {
    width: 100%;
    height: 150px;
    background: mediumSeaGreen;
    position: relative;
}

#rotator {
    width: 300px;
    height: 150px;
    margin: 0 auto;
    position: relative;
}

#rotator > #controls {
    list-style: none;
    position: absolute;
    bottom: 10px;
    height: 10px;
    width: 100%;
    z-index: 50;
}

#rotator > #controls > li {
    list-style: none;
    float: left;
}

#rotator > #controls > li > a {
    margin-right: 10px;
    width: 10px;
    height: 10px;
    background: mediumSeaGreen;
    z-index: 555;
    display: block;
    text-decoration: none;
}

#rotator > #controls > li > a.active {
    background: mediumSlateBlue; 
}

#rotator > #banners > div {
    width: 300px;
    height: 120px;
    margin: 0 auto;
    position: absolute;
    bottom: 0;
    display: none;
    z-index: 10;
}

#slide1 {
    background: black;
    border-radius: 5px 5px 0 0;
}

#slide2 {
    background: #fff;
    border-radius: 5px 5px 0 0;
}

#slide3 {
    background: #ff7200;
    border-radius: 5px 5px 0 0;
}

#slide4 {
    background: #c8c8c8;
    border-radius: 5px 5px 0 0;
}

JavaScript

// Slideshow functionality by Joshua Powell and Shane Vorachek.
// jsfiddle url: http://jsfiddle.net/Josh_Powell/mN93N/4/
$(document).ready(function() {
    function rotateInit() {
        var banners = $('#rotator > #banners > div');
        var count = banners.length;
        var i = 0;
        
        banners.first().show();
        
        function rotate() {
            i ++;
            
            var currentImage = $('#slide' + i);
            var nextImage = $('#slide' + (i + 1));
            
            nextImage.fadeIn('slow');
            currentImage.fadeOut('slow');
            
            $('.rotator-control').removeClass('active');
            $('#cont-' + (i + 1)).addClass('active');
            
            if (i === count) {
                $('#slide1').fadeIn('fast');
                $('#cont-1').addClass('active');
                i = 0;   
            }
        }
        
        function buildControls() {
            var controls = $('#controls');
            var i = 0;
            banners.each(function() {
                i++;
                controls.append('<li><a href="#" class="rotator-control" id="cont-' + i + '">&nbsp;</a></li>');
                $('#cont-1').addClass('active');
            });
        }
        
        buildControls();
        
        var rotateInterval = setInterval(rotate, 4000);
        rotateInterval;
    }
    
    rotateInit();
});