Skip to content

Instantly share code, notes, and snippets.

@iankit3
Created February 29, 2024 06:53
Show Gist options
  • Save iankit3/7071300a3cd20b4a834f76821a0c788d to your computer and use it in GitHub Desktop.
Save iankit3/7071300a3cd20b4a834f76821a0c788d to your computer and use it in GitHub Desktop.
Simple carousel
<div id="root"></div>
<template id="card-template">
<article class="card-container">
<figure class="card">
<img width="200" height="300" alt="no-alt" class="card-image" />
<figcaption class="card-caption"></figcaption>
</figure>
</article>
</template>
const root = document.getElementById("root");
const cardTemplate = document.getElementById("card-template");
const [width, height] = [300, 400];
function getImageURL(i) {
return `https://picsum.photos/seed/${i}/${width}/${height}`;
}
function init() {
const section = document.createElement("section");
section.classList.add("gallery");
const N = 5;
for (let i = 0; i < 5; ++i) {
const card = cardTemplate.content.cloneNode(true);
const image = card.querySelector(".card-image");
image.src = getImageURL(i);
image.style.width = width;
image.height = height;
const caption = card.querySelector(".card-caption");
caption.innerText = "caption";
section.appendChild(card);
}
root.appendChild(section);
}
init();
section.gallery {
display: flex;
width: 300px;
height: 400px;
overflow: hidden;
overflow-x: scroll;
align-items: center;
justify-content: center;
background: #2f2f2f;
margin: auto;
scroll-snap-type: x mandatory;
overscroll-behavior-x: contain;
&::-webkit-scrollbar {
display: none;
}
scrollbar-width: none;
.card-container {
width: 100%;
flex: 0 0 100%;
scroll-snap-align: center;
.card {
border: 1px solid;
margin: 0;
.card-image {
object-fit: contain;
width: 100%;
aspect-ratio: 4 / 3;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment