Carousel

interview question

by leethelobster

HTML

<div class="slideshow">
  <button id="button-prev">Previous</button>
  <div class="slideshow-articles">
    <div class="slideshow-articles-inner"></div>
  </div>
  <button id="button-next">Next</button>
</div>

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.slideshow > * {
  display: inline-block;
  vertical-align: middle;
}
.slideshow-articles {
  //width: 300px;
  height: 100px;
  overflow: hidden;
}
.slideshow-articles-inner {
  //width: 1000px;
  position: relative;
  left: 0;
}
.slideshow-box {
  //background-image: url('http://lorempixel.com/100/100');
  width: 100px;
  float: left;
  height: 100px;
  padding: 0;
}

JavaScript

// create carousel
// keyboard function working
// loop with clicking next and prev

var boxWidth = 100;
var imagesPerRow = 2;
var currentPage = 0;
var images = [{
	title: 'poop',
  image: 'http://lorempixel.com/100/100/sports/1'
}, {
	title: 'poop',
  image: 'http://lorempixel.com/100/100/sports/2'
}, {
	title: 'poop',
  image: 'http://lorempixel.com/100/100/sports/3'
}, {
	title: 'poop',
  image: 'http://lorempixel.com/100/100/sports/4'
}, {
	title: 'poop',
  image: 'http://lorempixel.com/100/10/sports/5'
}, {
	title: 'poop',
  image: 'http://lorempixel.com/100/100/sports/6'
}];

function buildHandlers() {
	var html = '';
  images.forEach(function(item, idx, images) {
  	html += '<div class="slideshow-box" style="background-image:url('+item.image+')"><h1>'+item.title+'</h1></div>';
  });
	$('.slideshow-articles-inner').html(html);
  
  $('.slideshow-articles').css({
		width: (imagesPerRow * boxWidth) + 'px'
  });
  $('.slideshow-articles-inner').css({
  	width: (images.length * boxWidth) + 'px'
  });
}

function eventHandlers() {
	$('#button-next').on('click', function() {
  	currentPage++;
		// disable button
    $('#button-next').prop('disabled', false);
    var limit = images.length / imagesPerRow - 1;
    if (currentPage === limit) {
    	$(this).prop('disabled', true);
    } else {
    	$(this).prop('disabled', false);
    }
    
    console.log('nxt', currentPage);
    // move it
  	var value = - (currentPage * imagesPerRow * boxWidth) + 'px';
    $('.slideshow-articles-inner').css('left', value);
  });

  $('#button-prev').on('click', function() {
		currentPage--;
    // disable button
    $('#button-prev').prop('disabled', false);
    if (currentPage === 0) {
    	$(this).prop('disabled', true);
    } else {
    	$(this).prop('disabled', false);
    }  
    console.log('prev', currentPage);
    // move it
  	var value = - (currentPage * imagesPerRow * boxWidth) + 'px';
    $('.slideshow-articles-inner').css('left', value);
  });
}
function init()...