(JS) Super simple slider/carousel/slideshow

By | August 14, 2015

Here’s how you can make a super simple slideshow that changes slides on a timer interval. You could easily edit it so any other event, like a mouse click, will trigger the slide() function.

You can see it in action HERE

HTML

<div class="slider">

    <div class="slide red">
        <p>THIS IS SLIDE 1</p>
    </div>

    <div class="slide blue">
        <p>THIS IS SLIDE 2</p>
    </div>

    <div class="slide green">
        <p>THIS IS SLIDE 3</p>
    </div>

</div>

CSS

.slider {
    width: 500px;
    height: 300px;
    margin: 0 auto;

    /* DON'T CHANGE THESE */
    position: relative;
    overflow: hidden;
}

.slide {
    /* DON'T CHANGE THESE */
    position: absolute;
    width: 100%;
    height: 100%;
}

/** ONLY FOR STYLING THE EXAMPLE SLIDES */
.slide p {
    color: #FFF;
    text-align: center;
}

.red {
    background: red;
}

.blue {
    background: blue;
}

.green {
    background: green;
}

jQuery

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
    // Configurable values
    slider = $('.slider'); // Slider element
    slideDuration = 3000; // Duration of each slide in milliseconds
    slideSpeed = 1000; // Speed of slide animation in milliseconds (must be equal of less than slideDuration)


    width = slider.width();
    slider.children().hide().css({left: width});
    slider.children(':first').show().css({left: 0});

    // Slide in from the left
    $.fn.slideIn = function () {
        $(this).show().animate({
            left: "-=" + width
        }, slideSpeed / 2);
    }

    // Slide out to the left
    $.fn.slideOut = function () {
        $(this).animate({
            left: "-=" + width
        }, slideSpeed / 2, function () {
            $(this).hide().css({left: width});
        });
    }

    // Main slide function
    function slide() {
        currentSlide = slider.find('div:visible:first');
        nextSlide = (!slider.children(":last").is(":visible")) ? currentSlide.next() : slider.children(':first');

        currentSlide.slideOut();
        nextSlide.slideIn();
    }

    // Timer function
    window.setInterval(function () {
        slide();
    }, slideDuration);
</script>

And of course you could make this dynamic by spitting out the slides from a database… for example like this:

<div class="slider">

<?php foreach ($slides as $slide) { ?>

    <div class="slide">
        <p><?php $slide['content'] ?></p>
    </div>

<?php } ?>

</div>

2 thoughts on “(JS) Super simple slider/carousel/slideshow

  1. Vince

    Hello! It seems to be a great and simple trick, but i’m trying to set in on an LARAVEL website, and it doesn’t
    work. The green slide shows up, but dont jump to another… Any idea?

    Reply

Leave a Reply to Vince Cancel reply

Your email address will not be published. Required fields are marked *