jQuery: responsive carousel

by gabrieleromanato

HTML

<div id="carousel">
    <div id="carousel-wrapper">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
        <div class="item">5</div>
    </div>
    <div id="carousel-nav">
        <a href="#" id="previous">Previous</a>
        <a href="#" id="next">Next</a>
    </div>
</div>

CSS

#carousel {
    width: 100%;
    max-width: 500px;
    margin: 2em auto;
    overflow: hidden;
    border: 2px solid gray;
}

#carousel-wrapper {
    height: 100px;
    width: 1500px;
    position: relative;
    background: silver;
}

div.item {
    height: 100%;
    line-height: 100px;
    text-align: center;
    width: 200px;
    margin-right: 1em;
    background: yellow;
    float: left;
}

#carousel-nav {
    margin: 1em 0;
    text-align: center;
}

#carousel-nav a {
    color: #fff;
    background: #000;
    padding: 0.2em 0.5em;
    text-decoration: none;
    margin-right: 1em;
}

JavaScript

(function($) {

    if (typeof $.fn.carousel !== 'function') {

        $.fn.carousel = function(options) {

            var self = this;
            var settings = {
                wrapper: '#carousel-wrapper',
                item: 'div.item',
                previous: '#previous',
                next: '#next',
                speed: 600
            };

            options = $.extend(settings, options);

            var $width = $(options.item).eq(0).width();

            return self.each(function() {

                $(options.previous).click(function(e) {

                    e.preventDefault();

                    $(options.wrapper).animate({
                        left: '-=' + $width
                    }, options.speed, 'linear');

                });


                $(options.next).click(function(e) {

                    e.preventDefault();

                    $(options.wrapper).animate({
                        left: '+=' + $width
                    }, options.speed, 'linear');

                });

            });

        };

    }


})(jQuery);

$('#carousel').carousel();