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: 0 auto;
    padding: 2em;
  }
</style>

<div class="site-container">
  <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>
              
            
!

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;
}

/* Box-sizing reset */
*,
*::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
 *
 * A simple customizable carousel built with plain JavaScript which can
 * be the starting point to build your own carousel solution.
 *
 * @constructor
 * @param   {Object} Configuration options for the carousel.
 * @param   {string} config.carouselSelector - CSS selector for the carousel container element.
 * @param   {string} config.slideSelector - CSS selector for the individual slide elements within the carousel.
 * @param   {boolean} [config.enablePagination=true] - Whether to enable pagination for the carousel.
 * @param   {boolean} [config.enableAutoplay=true] - Whether to enable autoplay for the carousel.
 * @param   {number} [config.autoplayInterval=2000] - Autoplay interval in milliseconds.
 * @returns {Object} An object containing methods to control the carousel.
 * @returns {Function} create - A function to create and initialize the carousel.
 * @returns {Function} destroy - A function to destroy and clean up the carousel.
 * @author  Rahul C.
 * @see     https://github.com/c99rahul/js-carousel
 */
const JSCarousel = ({
  carouselSelector,
  slideSelector,
  enablePagination = true,
  enableAutoplay = true,
  autoplayInterval = 2000
}) => {
  // Find the carousel element in the DOM.
  const carousel = document.querySelector(carouselSelector);

  // If carousel element is not found, log an error and exit.
  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 exit.
  if (!slides.length) {
    console.error("Specify a valid selector for slides.");
    return null;
  }

  /*
   * Initialize variables to keep track of carousel state and
   * references to different elements.
   */
  let currentSlideIndex = 0;
  let prevBtn, nextBtn;
  let autoplayTimer;
  let paginationContainer;

  /*
   * 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 to the element.
      Object.entries(attributes).forEach(([key, value]) => {
        element.setAttribute(key, value);
      });
    }

    if (children) {
      // Set content to 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;
  };

  /*
   * Modify the DOM structure and add required containers and controls
   * to the carousel element.
   */
  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 from the carousel element to the carousel inner
     * container to facilitate alignment.
     */
    slides.forEach((slide) => {
      carouselInner.appendChild(slide);
    });

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

    // Create and append next button.
    nextBtn = addElement(
      "btn",
      {
        class: "carousel-btn carousel-btn--prev-next carousel-btn--next",
        "aria-label": "Next Slide"
      },
      ">"
    );
    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 alignment styles for the slides, inject pagination
     * buttons, and attach event listeners to them.
     */
    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);
        });
      }
    });
  };

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

  /*
   * Update the state of pagination buttons according to the currently
   * selected slide.
   */
  const updatePaginationBtns = () => {
    const paginationBtns = paginationContainer.children;
    const prevActiveBtns = Array.from(paginationBtns).filter((btn) =>
      btn.classList.contains("carousel-btn--active")
    );
    prevActiveBtns.forEach((btn) => {
      btn.classList.remove("carousel-btn--active");
      btn.removeAttribute("aria-selected");
    });

    const currActiveBtns = paginationBtns[currentSlideIndex];
    if (currActiveBtns) {
      currActiveBtns.classList.add("carousel-btn--active");
      currActiveBtns.setAttribute("aria-selected", true);
    }
  };

  // Update the overall carousel state.
  const updateCarouselState = () => {
    if (enablePagination) {
      updatePaginationBtns();
    }
    adjustSlidePosition();
  };

  // Move slide left and right based on direction provided.
  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 event.
  const handlePaginationBtnClick = (index) => {
    currentSlideIndex = index;
    updateCarouselState();
  };

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

  // Start autoplaying of slides.
  const startAutoplay = () => {
    autoplayTimer = setInterval(() => {
      moveSlide("next");
    }, autoplayInterval);
  };

  // Stop autoplaying of slides.
  const stopAutoplay = () => clearInterval(autoplayTimer);

  /* Event handlers to manage autoplaying intelligentally on mouse
   * enter and leave events.
   */
  const handleMouseEnter = () => stopAutoplay();
  const handleMouseLeave = () => startAutoplay();

  // Attach event listeners to relevant elements.
  const attachEventListeners = () => {
    prevBtn.addEventListener("click", handlePrevBtnClick);
    nextBtn.addEventListener("click", handleNextBtnClick);

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

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

  // Destroy the carousel/clean-up.
  const destroy = () => {
    // Remove event listeners.
    prevBtn.removeEventListener("click", handlePrevBtnClick);
    nextBtn.removeEventListener("click", handleNextBtnClick);
    if (enablePagination) {
      const paginationBtns = paginationContainer.querySelectorAll(
        ".carousel-btn"
      );
      if (paginationBtns.length) {
        paginationBtns.forEach((btn) => {
          btn.removeEventListener("click", handlePaginationBtnClick);
        });
      }
    }

    // Clear autoplay intervals if autoplay is enabled.
    if (enableAutoplay && autoplayInterval !== null) {
      carousel.removeEventListener("mouseenter", handleMouseEnter);
      carousel.removeEventListener("mouseleave", handleMouseLeave);
      stopAutoplay();
    }
  };

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

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

carousel1.create();

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

              
            
!
999px

Console