JSFiddle - React, Tailwind, and code Playground

by Joerian Gauten

HTML

<div id="carousel">
    
    <div class="viewport">
        <ul class="slide-holder">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
    </div>
    
    <p class="nav-carousel"></p>
</div>

SCSS

.viewport {
    width:200px;
    overflow:hidden;
}
.slide-holder {
    margin:0;
    white-space:nowrap;
    line-height:0;
    font-size:0;
    padding:0;
    
    li {
        width:200px;
        height:150px;
        display:inline-block;
        background:green;
        line-height:150px;
        font-size:14px;
        text-align:center;
    }
    
    li:nth-child(2n+1) {
        background:blue;
    }
}

.nav-carousel a {
    text-decoration:none;
    text-indent:-999em;
    width:10px;
    height:10px;
    margin:2px;
    background:yellow;
    display:inline-block;
    border-radius:50%;
    box-shadow:0 0 2px black;
    
    &.active {
        background:green;
        box-shadow:inset 0 0 2px lightgrey;
    }
}

JavaScript

// get elements
var carousel = $('#carousel'),
    viewport = $('.viewport', carousel),
    slide_holder = $('.slide-holder', viewport),
    slides = $('li', slide_holder)
    slides_nav = $('.nav-carousel', carousel);

// init nav
$.each(slides, function(index, el) {
    var nav = $('<a/>');
    nav.attr('href', "#"+(index+1))
        .text(index+1)
        .appendTo(slides_nav);
});

slides_nav.find('a').eq(0).addClass('active');

$('a', slides_nav).on('click', function(e) {
    e.preventDefault();
    
    if ($(this).is('.active')) return;
    
    $(this).addClass('active').siblings().removeClass('active');
    change_slide($(this).index());
    
    
});


// move carousel
function change_slide(index) {
    
    slide_holder.stop().animate({
        marginLeft: -(slides.width()*index)
    }, 1000);
}