JSFiddle - React, Tailwind, and code Playground

by Tyler N.

HTML

<ul class="carousel">
    <li id="slide-1-slide" class="one slide">Slide 1</li>
    <li id="slide-2-slide" class="two slide">Slide 2</li>
    <li id="slide-3-slide" class="three slide">Slide 3</li>
    <li id="slide-4-slide" class="four slide">Slide 4</li>
</ul>

<ul class="pagination">
    <li class="nav-icon" id="slide-1">one</li>
    <li class="nav-icon" id="slide-2">two</li>
    <li class="nav-icon" id="slide-3">three</li>
    <li class="nav-icon" id="slide-4">four</li>
</ul>

CSS

.carousel {
    position:relative;
    height:320px;
    width:320px;
}

.carousel li {
    position:absolute;
    left:0;
    top:0;
    height:320px;
    width:320px;
}

.one { background: url(http://placekitten.com/g/300/300) no-repeat 0 center;
}
.two { background: url(http://placekitten.com/200/300) no-repeat 0 center;
}
.three { background: url(http://placekitten.com/300/200) no-repeat 0 center;
}
.four { background: url(http://placekitten.com/g/250/250) no-repeat 0 center;
}

.pagination {
    width: 100%;
    margin: 0;
    padding: 0;
}

.pagination li {
    display: inline-block;
    vertical-align: top;
    text-align: center;
    width: 23%;
    cursor: pointer;
}

JavaScript

$('.carousel li:gt(0)').hide();

//initialize carousel - works
function startInt() {
    ourInterval = setInterval(function () {
        $('.carousel li:first-child').fadeOut('slow')
            .next('li')
            .delay(1000)
            .fadeIn('slow')
            .end()    
            .appendTo('.carousel');
    }, 4000);
}startInt();


// rebuild carousel with pagination - NEEDS HELP
$('.nav-icon').click(function() {
    clearInterval(ourInterval);
    //this needs help, kind of works, doesn't rebuild in the right order.
    
    //hiding all slides first
    $('.slide').fadeOut('slow');

    //rebuild carousel showing the one that had it's pagination icond clicked *not working as expected*    
    $($('#' + this.id + '-slide')
      .prevAll('li')
      .get()
      .reverse())
      .appendTo('.carousel');
    
    $('#' + this.id + '-slide')
        .delay(1000)
        .fadeIn('slow')
        .end();
    
    startInt();
});


// pause and restart carousel - works
$('.carousel').mouseenter(function() {
    clearInterval(ourInterval);
});

$('.carousel').mouseleave(function() {
    startInt(ourInterval);
});