JSFiddle - React, Tailwind, and code Playground

by Arturo Schreiber

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="slider">
       <ul>
           <li><img src="http://gimepix.com/img/600-300-movies-001" alt="image1"></li>
           <li><img src="http://gimepix.com/img/600-300-movies-002" alt="image2"></li>
           <li><img src="http://gimepix.com/img/600-300-movies-003" alt="image3"></li>
           <li><img src="http://gimepix.com/img/600-300-movies-004" alt="image4"></li>
       </ul>
   </div>
   <div id="slider-nav">
       <button data-dir="prev">Previous</button>
       <button data-dir="next">Next</button>
   </div>

CSS

body {
    width:600px;
    margin:100px auto 0;
}
* {
    margin:0;
    padding:0;
}

#slider-nav {
    display:none;
    margin-top:1em;
}
#slider-nav button {
    padding:1em;
    margin-right:1em;
    border-radius: 10px;
    cursor:pointer;
}
.slider {
    width:inherit;
    height:300px;
    overflow:hidden;
}

.slider ul {
    width:10000px;
    list-style:none;
    
}

.slider li {
    float: left;
}

JavaScript

jQuery(document).ready(function(){
        
   
    (function($){
        var sliderUL = $('div.slider').children('ul'),
        images = sliderUL.find('img'),                    
        imagesLen = images.length,
        current = 1,
        imgWidth = images[0].width; // giving 0 instead of 600??
        console.log(imgWidth); //debug to console
        // var imgWidth = 600; // over ride error by manually setting imgWidth :(
        totalImgsWidth = imagesLen * imgWidth;
              
              
        $('#slider-nav').fadeIn(800).find('button').on("click", function(){
            var direction = $(this).data('dir'),
            loc = imgWidth;
            console.log(images[0].width);  // now giving the correct value of 600?? when a button is clicked?
            (direction === 'next') ? ++current : --current;
            
            if( current === 0){
                current = imagesLen;
                direction = "next";
            } else if( current -1 === imagesLen){
                current = 1;
                loc = 0;
            }
            
            transition(sliderUL, loc, direction);
        });
        
        function transition( container, loc, direction ) {
            var unit;
            if(direction && loc !== 0){
                unit = (direction === 'next') ? '-=' : '+=';
            }
            container.animate({
               'margin-left': unit ? (unit + loc) : loc
            });
        }
    })(jQuery);
        
         });