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

Save Automatically?

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

              
                <div
  class="carousel"
  role="region"
  aria-label="gallery"
  x-data="carousel"
>
  <div class="relative">
    <!-- controls -->
    <ul aria-label="gallery controls" role="list">	
      <li>
        <button class="arrow arrow--prev" @click="go('prev')">
          <div class="sr-only">Previous</div>
          <svg height="13" width="13" aria-hidden="true" fill="none" viewBox="0 0 6 10" xmlns="http://www.w3.org/2000/svg"><path d="M5 9.4.6 5 5 .6" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>
        </button>
      </li>
      <li>
        <button class="arrow arrow--next" @click="go('next')">
          <div class="sr-only">Next</div>
          <svg height="13" width="13" aria-hidden="true" fill="none" viewBox="0 0 6 10" xmlns="http://www.w3.org/2000/svg"><path d="M1 .6 5.4 5 1 9.4" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>
        </button>
      </li>
    </ul>

    <!-- carousel scroller -->
    <ul
        class="carousel__scroll"
        :class="{
          'carousel__scroll--active': momentum.active,
          'carousel__scroll--dragging': momentum.dragging
        }"
        role="list"
        tabindex="0"
        aria-label="gallery images"
    >
      <li class="carousel__slide">
        <img class="image" src="https://source.unsplash.com/ePpaQC2c1xA/700x700/" width="700" height="700" alt="" loading="lazy" decoding="async">
      </li>
      <li class="carousel__slide">
        <img class="image" src="https://source.unsplash.com/phIFdC6lA4E/700x700/" width="700" height="700" alt="" loading="lazy" decoding="async">
      </li>
      <li class="carousel__slide">
        <img class="image" src="https://source.unsplash.com/9wg5jCEPBsw/700x700/" width="700" height="700" alt="" loading="lazy" decoding="async">
      </li>
      <li class="carousel__slide">
        <img class="image" src="https://source.unsplash.com/g30P1zcOzXo/700x700/" width="700" height="700" alt="" loading="lazy" decoding="async">
      </li>
      <li class="carousel__slide">
        <img class="image" src="https://source.unsplash.com/73F4pKoUkM0/700x700/" width="700" height="700" alt="" loading="lazy" decoding="async">
      </li>
    </ul>
  </div>

  <ul class="pagination" role="list" aria-label="pagination">
    <li>
      <button
        class="pagination__item"
        @click="go(0)"
        :aria-pressed="(index === 0).toString()"
      >
        <div class="sr-only">go to page 1 of 1</div>
        <img src="https://source.unsplash.com/ePpaQC2c1xA/40x40/" width="40" height="40" alt="" loading="lazy" decoding="async">
      </button>
    </li>
    <li>
      <button
        class="pagination__item"
        @click="go(1)"
        :aria-pressed="(index === 1).toString()"
      >
        <div class="sr-only">go to slide 2 of 5</div>
        <img src="https://source.unsplash.com/phIFdC6lA4E/40x40/" width="40" height="40" alt="" loading="lazy" decoding="async">
      </button>
    </li>
    <li>
      <button
        class="pagination__item"
        @click="go(2)"
        :aria-pressed="(index === 2).toString()"
      >
        <div class="sr-only">go to slide 3 of 5</div>
        <img src="https://source.unsplash.com/9wg5jCEPBsw/40x40/" width="40" height="40" alt="" loading="lazy" decoding="async">
      </button>
    </li>
    <li>
      <button
        class="pagination__item"
        @click="go(3)"
        :aria-pressed="(index === 3).toString()"
      >
        <div class="sr-only">go to slide 4 of 5</div>
        <img src="https://source.unsplash.com/g30P1zcOzXo/40x40/" width="40" height="40" alt="" loading="lazy" decoding="async">
      </button>
    </li>
    <li>
      <button
        class="pagination__item"
        @click="go(4)"
        :aria-pressed="(index === 4).toString()"
      >
        <div class="sr-only">go to slide 5 of 5</div>
        <img src="https://source.unsplash.com/73F4pKoUkM0/40x40/" width="40" height="40" alt="" loading="lazy" decoding="async">
      </button>
    </li>
  </ul>
</div>
              
            
!

CSS

              
                .carousel {
  position: relative;
  
  &__scroll {
    display: flex;
    gap: 1rem;
    overflow: auto;
		cursor: grab;
		-webkit-overflow-scrolling: touch;
		scroll-snap-type: x mandatory;
		scroll-behavior: smooth;
		user-select: none;
    background: #f8f8f8;

		&--active {
			scroll-snap-type: unset;
			scroll-behavior: unset;
		}

		&--dragging {
			cursor: grabbing;
		}

		// hide scrollbars
		scrollbar-width: none;

		&::-webkit-scrollbar {
			display: none;
		}
  }
  
  &__slide {
		scroll-snap-align: center;
    width: 100%;
    flex-shrink: 0;
  }
}

.arrow {
  position: absolute;
  top: calc(50% - 1rem);
  
  display: flex;
  justify-content: center;
  align-items: center;
  
  width: 2rem;
  height: 2rem;
  
  border-radius: 1rem;
  background: rgb(154, 63, 32);
  color: #fff;
  
  &--prev {
    left: -1rem;
  }
  
  &--next {
    right: -1rem;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: .5rem;
  margin-top: 1rem;
  
  &__item {
    padding: .5rem;
    border: 1px solid transparent;
    transition: border-color .2s;
    
    &[aria-pressed="true"] {
      border-color: #000;
    }
  }
}

/**
 * misc
 */
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border-width: 0;
}

.relative {
  position: relative;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

body {
  max-width: 30rem;
  padding: 2rem;
  margin: 0 auto;
  font-family: system-ui;
}

img {
  display: block;
  width: 100%;
  height: auto;
}

button {
  appearance: none;
  cursor: pointer;
  border: 0;
  padding: 0;
}
              
            
!

JS

              
                import Alpine from "https://cdn.skypack.dev/[email protected]";

Alpine.data('carousel', function carousel() {
	return {
		scrollEl: null,

		index: 0,

		momentum: {
			active: false,
			handler: null,
			dragging: false,
			velocity: 0,
			startPos: 0,
			scrollLeft: 0,
		},

		init() {
			this.scrollEl = this.$root.querySelector(".carousel__scroll");

			this.dragScroll();
			this.updateIndex();
		},

		// move the slider
		go(mode) {
			this.scrollEl.scrollLeft = this.getNewPos(mode);
		},

		// get the new position of the slider after movement
		getNewPos(mode) {
			const currentScroll = this.scrollEl.scrollLeft;
			const slideWidth = this.scrollEl.offsetWidth;
			const scrollWidth = this.scrollEl.scrollWidth;

			let newScrollPos = currentScroll;

			// next
			if (mode === "next") {
				newScrollPos += slideWidth;
				// we're within 20px of the end so loop to the start
				if (Math.abs(scrollWidth - newScrollPos) < 20) {
					newScrollPos = 0;
				}
				return newScrollPos;
			}

			// prev
			if (mode === "prev") {
				// we're within 20px of the beginning so loop to the end
				if (Math.abs(newScrollPos) < 20) {
					return scrollWidth - slideWidth;
				}
				return (newScrollPos -= slideWidth);
			}

			// an index
			const index = parseInt(mode);
			if (typeof index === "number") {
				return (newScrollPos = slideWidth * index);
			}
		},

		/**
		 * update index
		 */
		updateIndex() {
			const slides = [...this.$root.querySelectorAll(".carousel__slide")];

			const observer = new IntersectionObserver(
				(entries, observer) => {
					// get the state of what slides are visible
					const state = [];
					for (const entry of entries) {
						const index = slides.indexOf(entry.target);
						state[index] = entry.intersectionRatio > 0.5;
					}

					// set index to the first visible slide
					const index = state.findIndex((v) => v);
					if (index !== -1) this.index = index;
				},
				{
					root: this.scrollEl,
					threshold: 0.5,
				}
			);

			for (const slide of slides) {
				observer.observe(slide);
			}
		},

		/**
		 * momentum drag for mouse users
		 */
		dragScroll() {
			this.scrollEl.addEventListener("mousedown", (e) => {
				this.momentum.dragging = true;
				this.momentum.active = true;
				this.momentum.startPos = e.pageX - this.scrollEl.offsetLeft;
				this.momentum.scrollLeft = this.scrollEl.scrollLeft;

				this.cancelMomentum();
			});

			this.scrollEl.addEventListener("mouseup", () => {
				this.momentum.dragging = false;
				this.beginMomentum();
			});

			this.scrollEl.addEventListener("mouseleave", () => {
				this.momentum.dragging = false;
				this.beginMomentum();
			});

			this.scrollEl.addEventListener("mousemove", (e) => {
				if (!this.momentum.dragging) return;
				e.preventDefault();

				const x = e.pageX - this.scrollEl.offsetLeft;
				const walk = x - this.momentum.startPos;

				// store the previous scroll position
				const prevScrollLeft = this.scrollEl.scrollLeft;
				this.scrollEl.scrollLeft = this.momentum.scrollLeft - walk;

				// Compare change in position to work out drag speed
				this.momentum.velocity = this.scrollEl.scrollLeft - prevScrollLeft;
			});

			this.scrollEl.addEventListener("wheel", (e) => {
				this.cancelMomentum();
			});
      
      const images = this.scrollEl.querySelectorAll('img')
      for (let image of images) {
        image.addEventListener('dragstart', e => e.preventDefault())
      }
		},

		beginMomentum() {
			this.cancelMomentum();
			this.momentum.handler = requestAnimationFrame(() => this.momentumLoop());
		},

		cancelMomentum() {
			cancelAnimationFrame(this.momentum.handler);
		},

		momentumLoop() {
			this.scrollEl.scrollLeft += this.momentum.velocity;
			this.momentum.velocity *= 0.95; // slow the velocity slightly
			// are we still moving?
			if (Math.abs(this.momentum.velocity) > 0.5) {
				this.momentum.handler = requestAnimationFrame(() =>
					this.momentumLoop()
				);
			} else {
				this.momentum.active = false;
			}
		},
	};
})

Alpine.start()
              
            
!
999px

Console