Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <style>
  .site-container {
    max-width: 800px;
    margin: 3em auto;
    padding: 0 2em;
  }

  .demo-title {
    text-align: center;
    margin-bottom: 2em;
  }

  .carousel+.carousel {
    margin-top: 4em;
  }
</style>

<div class="site-container">
  <h1 class="demo-title">JavaScript Carousels</h1>
  <div id="carousel-1" class="carousel" role="region" aria-labelledby="carousel-1-title">
    <h2 class="carousel-title" id="carousel-1-title">
      Beautiful Landscapes
    </h2>
    <p class="carousel-description">
      An autoplaying carousel of landscapes with pagination enabled
    </p>
    <div class="slide" role="tabpanel" aria-labelledby="carousel-1-slide-1-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-1-slide-1-title">Nanda Kot peak</h3>
          <p>Mukteshwar, Uttarakhand</p>
        </div>

        <img src="https://source.unsplash.com/gkIXFjDRyDc/1600x700" alt="Nanda Kot peak" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-1-slide-2-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-1-slide-2-title">Manali Mountains</h3>
          <p>Manali, Himachal Pradesh</p>
        </div>
        <img src="https://source.unsplash.com/oIXJ839p55k/1600x700" alt="Manali Mountains" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-1-slide-3-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-1-slide-3-title">Aotearoa</h3>
          <p>New Zealand</p>
        </div>

        <img src="https://source.unsplash.com/MlWRXR18fAg/1600x700" alt="Aotearoa" width="800" height="350" />
      </div>
    </div>
    <div class="slide" role="tabpanel" aria-labelledby="carousel-1-slide-4-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-1-slide-4-title">Richmond Park</h3>
          <p>London, England</p>
        </div>

        <img src="https://source.unsplash.com/jlVEj8IDPQc/1600x700" alt="London’s Richmond Park" width="800" height="350" />
      </div>
    </div>
  </div>

  <div id="carousel-2" class="carousel" role="region" aria-labelledby="carousel-1-title">
    <h2 class="carousel-title" id="carousel-2-title">Delicious food</h2>
    <p class="carousel-description">
      An carousel of some food items with pagination and autoplaying
      disabled
    </p>
    <div class="slide" role="tabpanel" aria-labelledby="carousel-2-slide-1-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-2-slide-1-title">Red Curry</h3>
          <p>
            Clicked by
            <a href="https://unsplash.com/photos/flat-lay-photography-of-vegetable-soup-on-white-ceramic-cup-XoByiBymX20">Emy</a>
          </p>
        </div>

        <img src="https://source.unsplash.com/XoByiBymX20/1600x700" alt="Red Curry" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-2-slide-2-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-2-slide-2-title">Steamed dumplings</h3>
          <p>
            Clicked by
            <a href="https://unsplash.com/photos/three-white-dimsum-on-brown-bowl-D-vDQMTfAAU">Charles Deluvio</a>
          </p>
        </div>
        <img src="https://source.unsplash.com/D-vDQMTfAAU/1600x700" alt="Steamed dumplings" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-2-slide-3-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-2-slide-3-title">Salmon, veggies, and quinoa</h3>
          <p>
            Clicked by
            <a href="https://unsplash.com/photos/broccoli-with-meat-on-plate-mmnKI8kMxpc">Ella Olsson</a>
          </p>
        </div>

        <img src="https://source.unsplash.com/mmnKI8kMxpc/1600x700" alt="Salmon, veggies, and quinoa" width="800" height="350" />
      </div>
    </div>
  </div>

  <div id="carousel-3" class="carousel" role="region" aria-labelledby="carousel-3-title">
    <h2 class="carousel-title" id="carousel-3-title">Random Images</h2>
    <p class="carousel-description">
      A carousel of many random images to demonstrate a lot of pagination
      items
    </p>
    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-1-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-1-title">A random fruit</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?fruit" alt="Fruit" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-2-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-2-title">A random building</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?building" alt="Building" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-3-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-3-title">A random river</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?river" alt="River" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-4-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-4-title">A random tree</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?tree" alt="Tree" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-5-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-5-title">A random mountain</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?mountain" alt="Mountain" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-6-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-6-title">A random animal</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?animal" alt="Animal" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-7-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-7-title">A random car</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?car" alt="Car" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-8-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-8-title">A random vegetable</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?vegetable" alt="Vegetable" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-9-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-9-title">A random street</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?street" alt="Street" width="800" height="350" />
      </div>
    </div>

    <div class="slide" role="tabpanel" aria-labelledby="carousel-3-slide-10-title">
      <div class="slide-content">
        <div class="slide-caption">
          <h3 id="carousel-3-slide-10-title">A random tattoo</h3>
        </div>

        <img src="https://source.unsplash.com/random/1600x700/?tattoo" alt="Tattoo" width="800" height="350" />
      </div>
    </div>
  </div>
</div>
              
            
!

CSS

              
                :root {
  --carousel-height: 350px;
  --carousel-radius: 0.5em;
  --carousel-nav-btn-dim: 3em;
  --carousel-page-nav-btn-dim: 0.5em;
  --carousel-caption-padding: 2em;
  --carousel-caption-color: #fff;
  --carousel-caption-bg: linear-gradient(
    to bottom,
    transparent,
    hsl(0 0 0 / 65%) 80%
  );
  --carousel-inner-spacing: 2em;
  --carousel-prev-next-btn-bg: #fff;
  --carousel-prev-next-btn-color: #333;
  --carousel-pagination-margin: 1em;
  --carousel-pagination-gap: 0.75em;
  --carousel-pagination-btn-bg: #aaa;
  --carousel-pagination-btn-active-bg: #333;
}

*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 0;
  font: 1em/160% sans-serif;
}

img,
video,
iframe {
  max-width: 100%;
}

.carousel-inner {
  overflow: hidden;
  position: relative;
  min-height: var(--carousel-height);
  border-radius: var(--carousel-radius);
}

.carousel-title {
  margin-top: 0;
  margin-bottom: 0.5em;
}

.carousel-title + .carousel-description {
  color: #888;
  margin-top: 0;
}

.slide {
  width: 100%;
  height: 100%;
  position: absolute;
  transition: transform 0.5s cubic-bezier(0.42, 0, 0.58, 1);
}

.slide-content {
  position: relative;
  z-index: 5000;
  height: 100%;
}

.slide-caption {
  width: 100%;
  position: absolute;
  padding: var(--carousel-caption-padding);
  left: 0;
  bottom: 0;
  color: var(--carousel-caption-color);
  background-image: var(--carousel-caption-bg);
}

.slide-caption a {
  color: currentColor;
}

.slide-caption h3,
.slide-caption p {
  margin: 0;
}

.slide-caption p {
  font-size: 75%;
  opacity: 0.6;
}

.slide img {
  width: 100%;
  object-fit: cover;
}

.carousel-btn {
  width: var(--carousel-nav-btn-dim);
  height: var(--carousel-nav-btn-dim);
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  color: var(--carousel-prev-next-btn-color);
  background-color: var(--carousel-prev-next-btn-bg);
}

.carousel-btn--prev-next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  transition: transform 0.1s ease-in-out;
}

.carousel-btn--prev-next:hover {
  transform: translateY(-50%) scale(1.2);
}

.carousel-btn--prev {
  left: var(--carousel-inner-spacing);
}

.carousel-btn--next {
  right: var(--carousel-inner-spacing);
}

.carousel-pagination {
  margin-top: var(--carousel-pagination-margin);
  display: flex;
  gap: var(--carousel-pagination-gap);
  justify-content: center;
}

.carousel-pagination .carousel-btn {
  background-color: var(--carousel-pagination-btn-bg);
  height: var(--carousel-page-nav-btn-dim);
  width: var(--carousel-page-nav-btn-dim);
  border-radius: 50%;
  color: transparent;
  transition: transform 0.25s, background-color 0.25s ease-in-out;
}

.carousel-pagination .carousel-btn--active {
  transform: scale(1.5);
  background-color: var(--carousel-pagination-btn-active-bg);
}

              
            
!

JS

              
                /**
 * JavaScript Carousel
 *
 * This is a simple customizable carousel built with plain JavaScript,
 * which can be your starting point to build your own carousel solution.
 *
 * @author  Rahul C.
 * @link    https://github.com/c99rahul/js-carousel
 * @param   {*} param0
 * @param   {Object} config - Configuration options for the carousel.
 * @param   {string} config.carouselSelector - CSS selector for the carousel container element.
 * @param   {string|null} [config.slideSelector=null] - CSS selector for the individual slide elements within the carousel.
 * @param   {boolean} [config.enableAutoplay=true] - Whether to enable autoplay for the carousel.
 * @param   {number|null} [config.autoplayInterval=2000] - Autoplay interval in milliseconds.
 * @param   {boolean} [config.enablePagination=true] - Whether to enable pagination for the carousel.
 * @returns {JSCarousel} Am instance of JSCarousel.
 */
const JSCarousel = ({
  carouselSelector,
  slideSelector = null,
  enableAutoplay = true,
  autoplayInterval = 2000,
  enablePagination = true
}) => {
  // Initialize variables to keep track of carousel state
  let currentSlideIndex = 0;
  let prevBtn, nextBtn;
  let autoplayTimer;
  let paginationContainer;

  // Find the carousel element in the DOM
  const carousel = document.querySelector(carouselSelector);

  // If carousel element is not found, log an error and return null
  if (!carousel) {
    console.error("Specify a valid selector for the carousel.");
    return null;
  }

  // Find all slides within the carousel
  const slides = carousel.querySelectorAll(slideSelector);

  // If no slides are found, log an error and return null
  if (!slides.length) {
    console.error("Specify a valid selector for slides.");
    return null;
  }

  /*
   * Utility function to create and append HTML elements with
   * attributes and children
   */
  const addElement = (tag, attributes, children) => {
    const element = document.createElement(tag);

    if (attributes) {
      // Set attributes for the element
      Object.entries(attributes).forEach(([key, value]) => {
        element.setAttribute(key, value);
      });
    }

    if (children) {
      // Set content for the element
      if (typeof children === "string") {
        element.textContent = children;
      } else {
        children.forEach((child) => {
          if (typeof child === "string") {
            element.appendChild(document.createTextNode(child));
          } else {
            element.appendChild(child);
          }
        });
      }
    }

    return element;
  };

  /*
   * Function to modify the DOM structure to fit the carousel's
   * requirements
   */
  const tweakStructure = () => {
    carousel.setAttribute("tabindex", "0");

    // Create a div for carousel inner content
    const carouselInner = addElement("div", {
      class: "carousel-inner"
    });
    carousel.insertBefore(carouselInner, slides[0]);

    // Move slides into the carousel inner container
    slides.forEach((slide) => {
      carouselInner.appendChild(slide);
    });

    // Create and append previous and next buttons
    prevBtn = addElement(
      "btn",
      {
        class: "carousel-btn carousel-btn--prev-next carousel-btn--prev",
        "aria-label": "Previous Slide"
      },
      "<"
    );

    nextBtn = addElement(
      "btn",
      {
        class: "carousel-btn carousel-btn--prev-next carousel-btn--next",
        "aria-label": "Next Slide"
      },
      ">"
    );

    carouselInner.appendChild(prevBtn);
    carouselInner.appendChild(nextBtn);

    // If pagination is enabled, create and append pagination buttons
    if (enablePagination) {
      paginationContainer = addElement("nav", {
        class: "carousel-pagination",
        role: "tablist"
      });
      carousel.appendChild(paginationContainer);
    }

    /*
     * Set initial styles and event listeners for slides and pagination
     * buttons
     */
    slides.forEach((slide, index) => {
      slide.style.transform = `translateX(${index * 100}%)`;
      if (enablePagination) {
        const paginationBtn = addElement(
          "btn",
          {
            class: `carousel-btn caroursel-btn--${index + 1}`,
            role: "tab"
          },
          `${index + 1}`
        );

        paginationContainer.appendChild(paginationBtn);

        if (index === 0) {
          paginationBtn.classList.add("carousel-btn--active");
          paginationBtn.setAttribute("aria-selected", true);
        }

        paginationBtn.addEventListener("click", () => {
          handlePaginationBtnClick(index);
        });
      }
    });
  };

  // Function to adjust slide positions
  const adjustSlidePosition = () => {
    slides.forEach((slide, i) => {
      slide.style.transform = `translateX(${100 * (i - currentSlideIndex)}%)`;
    });
  };

  // Function to update pagination buttons
  const updatePaginationBtns = () => {
    const btns = paginationContainer.children;
    const prevActiveBtns = Array.from(btns).filter((btn) =>
      btn.classList.contains("carousel-btn--active")
    );
    const currentActiveBtn = btns[currentSlideIndex];

    prevActiveBtns.forEach((btn) => {
      btn.classList.remove("carousel-btn--active");
      btn.removeAttribute("aria-selected");
    });
    if (currentActiveBtn) {
      currentActiveBtn.classList.add("carousel-btn--active");
      currentActiveBtn.setAttribute("aria-selected", true);
    }
  };

  // Function to update carousel state
  const updateCarouselState = () => {
    if (enablePagination) {
      updatePaginationBtns();
    }
    adjustSlidePosition();
  };

  // Function to move slide based on direction
  const moveSlide = (direction) => {
    const newSlideIndex =
      direction === "next"
        ? (currentSlideIndex + 1) % slides.length
        : (currentSlideIndex - 1 + slides.length) % slides.length;
    currentSlideIndex = newSlideIndex;
    updateCarouselState();
  };

  // Event handler for pagination button click
  const handlePaginationBtnClick = (index) => {
    currentSlideIndex = index;
    updateCarouselState();
  };

  // Event handlers for previous and next button clicks
  const handlePrevBtnClick = () => moveSlide("prev");

  const handleNextBtnClick = () => moveSlide("next");

  // Event handler for keyboard navigation
  const handleKeyboardNav = (event) => {
    if (!carousel.contains(event.target)) return;
    if (event.defaultPrevented) return;

    switch (event.key) {
      case "ArrowLeft":
        moveSlide("prev");
        break;
      case "ArrowRight":
        moveSlide("next");
        break;
      default:
        return;
    }

    event.preventDefault();
  };

  // Function to start autoplay
  const startAutoplay = () => {
    autoplayTimer = setInterval(() => {
      moveSlide("next");
    }, autoplayInterval);
  };

  // Function to stop autoplay
  const stopAutoplay = () => clearInterval(autoplayTimer);

  // Event handlers for mouse enter and leave events for autoplay
  const handleMouseEnter = () => stopAutoplay();

  const handleMouseLeave = () => startAutoplay();

  // Attach event listeners to relevant elements
  const attachEventListeners = () => {
    prevBtn.addEventListener("click", handlePrevBtnClick);
    nextBtn.addEventListener("click", handleNextBtnClick);
    carousel.addEventListener("keydown", handleKeyboardNav);
    if (enableAutoplay && autoplayInterval !== null) {
      carousel.addEventListener("mouseenter", handleMouseEnter);
      carousel.addEventListener("mouseleave", handleMouseLeave);
    }
  };

  // Function to initialize the carousel
  const create = () => {
    tweakStructure();
    attachEventListeners();
    if (enableAutoplay && autoplayInterval !== null) {
      startAutoplay();
    }
  };

  // Function to destroy the carousel
  const destroy = () => {
    // Remove event listeners and stop autoplay if enabled
    if (enablePagination) {
      prevBtn.removeEventListener("click", handlePrevBtnClick);
      nextBtn.removeEventListener("click", handleNextBtnClick);
      carousel.removeEventListener("keydown", handleKeyboardNav);
    }

    if (enableAutoplay && autoplayInterval !== null) {
      carousel.removeEventListener("mouseenter", handleMouseEnter);
      carousel.removeEventListener("mouseleave", handleMouseLeave);
      stopAutoplay();
    }
  };

  /*
   * Return an object containing methods to create and destroy the
   * carousel
   */
  return { create, destroy };
};

const carousel1 = JSCarousel({
  carouselSelector: "#carousel-1",
  slideSelector: ".slide",
  enablePagination: true
});

carousel1.create();

const carousel2 = JSCarousel({
  carouselSelector: "#carousel-2",
  slideSelector: ".slide",
  enablePagination: false,
  enableAutoplay: false
});

carousel2.create();

const carousel3 = JSCarousel({
  carouselSelector: "#carousel-3",
  slideSelector: ".slide"
});

carousel3.create();

window.addEventListener("unload", () => {
  carousel1.destroy();
  carousel2.destroy();
});

              
            
!
999px

Console