Carousel

In this example below you will see how to do a Carousel with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by benjaminchadwick, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright benjaminchadwick ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Carousel</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  
<div class="carousel" id="carousel" data-slide="0">
  <div class="carousel-wrapper"><img src="https://i.imgsafe.org/2272925edb.jpeg" draggable="false"/><img src="https://i.imgsafe.org/22725ae93f.jpeg" draggable="false"/><img src="https://i.imgsafe.org/2272679b4b.jpeg" draggable="false"/><img src="https://i.imgsafe.org/227279db59.jpeg" draggable="false"/><img src="https://i.imgsafe.org/2272849807.jpeg" draggable="false"/><img src="https://i.imgsafe.org/2272925edb.jpeg" draggable="false"/><img src="https://i.imgsafe.org/22725ae93f.jpeg" draggable="false"/>
  </div>
  <button class="carousel-button carousel-left" type="button" value="left">〈</button>
  <button class="carousel-button carousel-right" type="button" value="right"> 〉</button>
  <button class="carousel-button carousel-playPause hidden" id="playPause"></button>
  <div class="carousel-goTo">
    <button class="carousel-button carousel-goToBtn active" type="button" value="0">●</button>
    <button class="carousel-button carousel-goToBtn" type-"button="type-"button" value="1">	●</button>
    <button class="carousel-button carousel-goToBtn" type-"button="type-"button" value="2">	●</button>
    <button class="carousel-button carousel-goToBtn" type-"button="type-"button" value="3">	●</button>
    <button class="carousel-button carousel-goToBtn" type-"button="type-"button" value="4">	●</button>
  </div>
</div>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/benjaminchadwick/carousel-dMaXyx */
@charset "UTF-8";
*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: black;
}

.hidden {
  display: none;
}

.carousel {
  height: 426px;
  margin: 2em auto;
  overflow: hidden;
  position: relative;
  width: 640px;
}

.carousel-wrapper {
  height: 100%;
  left: -640px;
  overflow: hidden;
  position: absolute;
  width: 4480px;
}

.sliding {
  transition: -webkit-transform .5s;
  transition: transform .5s;
  transition: transform .5s, -webkit-transform .5s;
}

.carousel-button {
  background-color: transparent;
  border: none;
  color: grey;
  cursor: pointer;
  font-weight: bold;
  height: 1em;
  position: absolute;
  z-index: 1;
}
.carousel-button:hover {
  color: white;
}

.carousel-left, .carousel-right {
  font-size: 4em;
  left: -1ex;
  top: calc(50% - .5em);
  width: 20px;
}

.carousel-right {
  left: auto;
  right: .3ex;
}

.carousel-playPause {
  bottom: 1em;
  left: 1em;
}

.pause:after {
  content: '▌▌';
}

.play:after {
  content: '►';
  display: block;
  font-size: 1.5em;
  margin-top: -.2em;
}

.carousel-goTo {
  bottom: 0;
  position: absolute;
  text-align: center;
  width: 100%;
}

.carousel-goToBtn {
  display: inline;
  position: static;
}
.carousel-goToBtn.active {
  color: white;
}


/*Downloaded from https://www.codeseek.co/benjaminchadwick/carousel-dMaXyx */
/*
  Use the arrows or click and drag.

  To change the images, simply update the array at the top of the Jade code.
  You will also need to update the variables $nbSlides in the Sass code and NBSLIDES in the JS
  
  The last image is repeated at the beginning, and the first is repeated at the end. This creates the illusion of a continuous loop.
  
  Photos downloaded from pexels.com - completely free and legal to copy - and hosted on imgsafe.org
*/

(function() {

  var NBSLIDES = 5; // the number of slides in the carousel
  var IMGWIDTH = 640; // the width, in px, of each image in the carousel
  var SLIDEDELAY = 5; // the time in seconds between each image. If this value is 0, the carousel does not slide automatically.

  // UTILITY FUNCTIONS
  var HELPERS = {
    // addClass, removeClass: from youmightnotneedjquery.com
    addClass: function(el, className) {
      if (el.classList) el.classList.add(className);
      else el.className += ' ' + className;
    },
    removeClass: function(el, className) {
      if (el.classList) el.classList.remove(className);
      else el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'g'), ' ');
    },
    eachElement: function(els, func) {
      // els: element list
      // func: function just like in array forEach
      Array.prototype.forEach.call(els, func);
    }
  };

  var carousel = document.getElementById('carousel');
  var wrapper = carousel.firstElementChild;

  HELPERS.eachElement(document.getElementsByClassName('carousel-button'), function(button) {
    button.addEventListener('click', slideAndUpdate);
  });

  // Click and Drag functionality
  (function() {
    var mousedown = false;
    var mousemoved = false;
    var x = 0; // x position of mouse
    function clickToDrag(event) {
      // triggered on mousedown or touchstart
      mousedown = true;
      if (event.touches && event.touches.length === 1) {
        x = event.touches[0].clientX;
      } else {
        x = event.clientX || 0;
      }
    }
    function drag(event) {
      var clientX = event.clientX;
      // triggered on mousemove or touchmove
      if (!mousedown || mousemoved) {
        return; // only act if mouse is down 
                // and move has not already been registered
      }
      mousemoved = true;
      if (event.changedTouches && 
          event.changedTouches.length === 1) {
        clientX = event.changedTouches[0].clientX;
      } else if (!clientX) {
        return; // don't act if not either click or single touch
      }
      if (clientX > x) {
        slideAndUpdate.call({value: 'left'});
      }
      if (clientX < x) {
        slideAndUpdate.call({value: 'right'});
      }
    }
    function unClick() {
      // triggered on mouseup
      mousedown = false;
      mousemoved = false;
    }
    carousel.addEventListener('mousedown', clickToDrag);
    carousel.addEventListener('mousemove', drag);
    carousel.addEventListener('mouseup', unClick);

    carousel.addEventListener('touchstart', clickToDrag);		
    carousel.addEventListener('touchmove', drag);		
    carousel.addEventListener('touchend', unClick);
  }) ();

  function slideAndUpdate() {
    if (currentPosition() !== -IMGWIDTH * carousel.dataset.slide) return;

    // sliding function
    // triggered when buttons are clicked
    // triggered from click and drag
    // carousel.dataset.slide : current slide value
    var oldSlideNb = parseInt(carousel.dataset.slide, 10); 
    if (this.value === 'left') { // left arrow button
      carousel.dataset.slide = (oldSlideNb + NBSLIDES - 1) % NBSLIDES;
    } else if (this.value === 'right') { // right arrow button
      carousel.dataset.slide = (oldSlideNb + 1) % NBSLIDES;
    } else { // round button at bottom
      var newSlideNb = parseInt(this.value, 10);
      if (!isNaN(newSlideNb) &&
          newSlideNb >= 0 && 
          newSlideNb < NBSLIDES) {
        carousel.dataset.slide = newSlideNb;
      } else return;
    }

    function slideTo(newPosition) {
      // slide with transition animation
      HELPERS.addClass(wrapper, 'sliding');
      moveTo(newPosition);
    }

    function moveTo(newPosition) {
      // change picture without transition animation
      wrapper.style.transform = 'translateX(' + newPosition + 'px)';
    }

    function currentPosition() {
      // output current position as a number of pixels
      if (!wrapper.style.transform.length) return 0;
      return parseInt(wrapper.style.transform.replace(/translateX\(|px\)/g, ''), 10);
    }

    wrapper.addEventListener('transitionend', function() {
      // remove transition when transition completes
      // reset position to correct value for image
      //   (for sliding left from the beginning or right from the end)
      HELPERS.removeClass(wrapper, 'sliding');
      moveTo(-IMGWIDTH * carousel.dataset.slide);
    });

    // special cases: sliding left from the beginning or right from the end
    if (this.value === 'left' && oldSlideNb === 0) {
      slideTo(IMGWIDTH);
    } else if (this.value === 'right' && oldSlideNb === NBSLIDES - 1) {
      slideTo(-NBSLIDES * IMGWIDTH);
    } else {
      slideTo(-IMGWIDTH * carousel.dataset.slide);
    }

    // make sure the correct round button is selected
    HELPERS.eachElement(
      carousel.getElementsByClassName('carousel-goToBtn'), 
      function(el) {
        if (carousel.dataset.slide == el.value) {
          HELPERS.addClass(el, 'active');
        } else {
          HELPERS.removeClass(el, 'active');
        }
      }
    );
  }

  (function() {
    var isRunning = false;
    var playPause = document.getElementById('playPause');
    var slideTimeout = 0;
    if (!isNaN(SLIDEDELAY) && SLIDEDELAY) {
      togglePlayPause();
      HELPERS.removeClass(playPause, 'hidden');
    }
    function togglePlayPause() {
      console.log('togglePlayPause');
      isRunning = isRunning ? false : true;
      if (isRunning) {
        HELPERS.removeClass(playPause, 'play');
        HELPERS.addClass(playPause, 'pause');
        autoslide();
      } else {
        HELPERS.removeClass(playPause, 'pause');
        HELPERS.addClass(playPause, 'play');
        clearTimeout(slideTimeout);
      }
    }
    playPause.addEventListener('click', togglePlayPause);
    function autoslide() {
      console.log('autoslide', Date.now());
      slideAndUpdate.call({value: 'right'});
      if (isRunning) slideTimeout = setTimeout(function() {
        requestAnimationFrame(autoslide);
      }, SLIDEDELAY*1000);
    }
  }) ();
}) ();

Comments