horizontal
Carousel
Pure vanilla JavaScript – no frameworks, no dependencies. A
horizontal virtual list rendering 10,000 cards with
orientation: 'horizontal' and
scroll.wheel: true. Toggle
variable width to switch between fixed-size cards
and dynamic per-item widths. Only visible items are in the DOM.
Source
// Carousel — Vanilla JavaScript
// Horizontal scrolling with toggle between fixed and variable item widths.
// Uses split-layout + panel + shared footer stats (same pattern as basic).
import { vlist } from "vlist";
import { items, buildConfig, getDetailHtml, ASPECT_RATIO } from "../shared.js";
import { createStats } from "../../stats.js";
// Scale factor: maps height 200–500 → 0–1
const MIN_HEIGHT = 200;
const MAX_HEIGHT = 500;
function getScale(h) {
return Math.max(0, Math.min(1, (h - MIN_HEIGHT) / (MAX_HEIGHT - MIN_HEIGHT)));
}
// =============================================================================
// State
// =============================================================================
let variableWidth = false;
let currentHeight = 240;
let currentGap = 8;
let currentRadius = 12;
let list = null;
// =============================================================================
// DOM references — panel
// =============================================================================
const toggleEl = document.getElementById("toggle-variable");
const sizeSlider = document.getElementById("size-slider");
const sizeValue = document.getElementById("size-value");
const gapButtons = document.getElementById("gap-buttons");
const radiusButtons = document.getElementById("radius-buttons");
const detailEl = document.getElementById("card-detail");
const listContainerEl = document.getElementById("list-container");
// =============================================================================
// DOM references — footer right side
// =============================================================================
const ftWidth = document.getElementById("ft-width");
const ftMode = document.getElementById("ft-mode");
// =============================================================================
// Stats — shared footer (progress, velocity, visible/total)
// =============================================================================
function getCurrentWidth() {
return Math.round(currentHeight * ASPECT_RATIO);
}
const stats = createStats({
getList: () => list,
getTotal: () => items.length,
getItemHeight: () => getCurrentWidth() + currentGap,
container: "#list-container",
});
// =============================================================================
// Footer — right side (contextual)
// =============================================================================
function updateContext() {
const w = getCurrentWidth();
if (ftWidth) ftWidth.textContent = variableWidth ? "var" : w;
if (ftMode) ftMode.textContent = variableWidth ? "variable" : "fixed";
}
// =============================================================================
// Create / Recreate list
// =============================================================================
function createList() {
if (list) {
list.destroy();
list = null;
}
listContainerEl.innerHTML = "";
listContainerEl.style.height = currentHeight + "px";
listContainerEl.style.setProperty("--card-scale", getScale(currentHeight));
listContainerEl.style.setProperty("--item-gap", currentGap + "px");
listContainerEl.style.setProperty("--item-radius", currentRadius + "px");
list = vlist({
container: "#list-container",
...buildConfig(variableWidth, currentHeight, currentGap),
}).build();
list.on("range:change", stats.scheduleUpdate);
list.on("scroll", stats.scheduleUpdate);
list.on("velocity:change", ({ velocity }) => stats.onVelocity(velocity));
list.on("item:click", ({ item, index }) => {
showDetail(item, index);
});
stats.update();
updateContext();
}
// =============================================================================
// Card detail (panel)
// =============================================================================
function showDetail(item, index) {
if (detailEl) {
detailEl.innerHTML = getDetailHtml(item, index, variableWidth);
}
}
// =============================================================================
// Size slider
// =============================================================================
sizeSlider?.addEventListener("input", (e) => {
currentHeight = parseInt(e.target.value, 10);
if (sizeValue) sizeValue.textContent = currentHeight + "px";
createList();
});
// =============================================================================
// Gap chips
// =============================================================================
gapButtons?.addEventListener("click", (e) => {
const btn = e.target.closest("[data-gap]");
if (!btn) return;
const gap = parseInt(btn.dataset.gap, 10);
if (gap === currentGap) return;
currentGap = gap;
gapButtons.querySelectorAll("button").forEach((b) => {
b.classList.toggle("ctrl-btn--active", parseInt(b.dataset.gap) === gap);
});
createList();
});
// =============================================================================
// Radius chips
// =============================================================================
radiusButtons?.addEventListener("click", (e) => {
const btn = e.target.closest("[data-radius]");
if (!btn) return;
const radius = parseInt(btn.dataset.radius, 10);
if (radius === currentRadius) return;
currentRadius = radius;
radiusButtons.querySelectorAll("button").forEach((b) => {
b.classList.toggle(
"ctrl-btn--active",
parseInt(b.dataset.radius) === radius,
);
});
createList();
});
// =============================================================================
// Toggle — variable width
// =============================================================================
toggleEl?.addEventListener("change", (e) => {
variableWidth = e.target.checked;
createList();
});
// =============================================================================
// Scroll To — smooth navigation buttons
// =============================================================================
document.getElementById("btn-start")?.addEventListener("click", () => {
list?.scrollToIndex(0, { align: "start", behavior: "smooth", duration: 600 });
});
document.getElementById("btn-center")?.addEventListener("click", () => {
list?.scrollToIndex(Math.floor(items.length / 2), {
align: "center",
behavior: "smooth",
duration: 800,
});
});
document.getElementById("btn-end")?.addEventListener("click", () => {
list?.scrollToIndex(items.length - 1, {
align: "end",
behavior: "smooth",
duration: 600,
});
});
// =============================================================================
// Init
// =============================================================================
createList();
<div class="container">
<header>
<h1>Carousel</h1>
<p class="description">
Pure vanilla JavaScript – no frameworks, no dependencies. A
horizontal virtual list rendering 10,000 cards with
<code>orientation: 'horizontal'</code> and
<code>scroll.wheel: true</code>. Toggle
<strong>variable width</strong> to switch between fixed-size cards
and dynamic per-item widths. Only visible items are in the DOM.
</p>
</header>
<div class="split-layout">
<div class="split-main">
<div id="list-container"></div>
</div>
<aside class="split-panel">
<!-- Mode -->
<section class="panel-section">
<h3 class="panel-title">Mode</h3>
<div class="panel-row">
<label class="panel-label">Size</label>
<span class="panel-value" id="size-value">240px</span>
</div>
<div class="panel-row">
<input
type="range"
id="size-slider"
class="panel-slider"
min="200"
max="500"
step="10"
value="240"
/>
</div>
<div class="panel-row">
<label class="panel-label">Variable width</label>
<label class="toggle">
<input type="checkbox" id="toggle-variable" />
<span class="toggle-track"></span>
</label>
</div>
<div class="panel-row">
<label class="panel-label">Gap</label>
<div class="panel-btn-group" id="gap-buttons">
<button class="ctrl-btn" data-gap="0">0</button>
<button class="ctrl-btn" data-gap="4">4</button>
<button class="ctrl-btn ctrl-btn--active" data-gap="8">
8
</button>
<button class="ctrl-btn" data-gap="12">12</button>
<button class="ctrl-btn" data-gap="16">16</button>
</div>
</div>
<div class="panel-row">
<label class="panel-label">Radius</label>
<div class="panel-btn-group" id="radius-buttons">
<button class="ctrl-btn" data-radius="0">0</button>
<button class="ctrl-btn" data-radius="4">4</button>
<button class="ctrl-btn" data-radius="8">8</button>
<button
class="ctrl-btn ctrl-btn--active"
data-radius="12"
>
12
</button>
<button class="ctrl-btn" data-radius="16">16</button>
</div>
</div>
</section>
<!-- Scroll To -->
<section class="panel-section">
<h3 class="panel-title">Scroll To</h3>
<div class="panel-row">
<div class="panel-btn-group">
<button
id="btn-start"
class="panel-btn panel-btn--icon"
title="Start"
>
<i class="icon icon--back"></i>
</button>
<button
id="btn-center"
class="panel-btn panel-btn--icon"
title="Center"
>
<i class="icon icon--center"></i>
</button>
<button
id="btn-end"
class="panel-btn panel-btn--icon"
title="End"
>
<i class="icon icon--forward"></i>
</button>
</div>
</div>
</section>
<!-- Card Detail -->
<section class="panel-section">
<h3 class="panel-title">Last clicked</h3>
<div class="panel-detail" id="card-detail">
<span class="panel-detail__empty"
>Click a card to preview</span
>
</div>
</section>
</aside>
</div>
<footer class="example-footer" id="example-footer">
<div class="example-footer__left">
<span class="example-footer__stat">
<strong id="ft-progress">0%</strong>
</span>
<span class="example-footer__stat">
<span id="ft-velocity">0.00</span> /
<strong id="ft-velocity-avg">0.00</strong>
<span class="example-footer__unit">px/ms</span>
</span>
<span class="example-footer__stat">
<span id="ft-dom">0</span> /
<strong id="ft-total">0</strong>
<span class="example-footer__unit">items</span>
</span>
</div>
<div class="example-footer__right">
<span class="example-footer__stat">
width <strong id="ft-width">260</strong
><span class="example-footer__unit">px</span>
</span>
<span class="example-footer__stat">
mode <strong id="ft-mode">fixed</strong>
</span>
</div>
</footer>
</div>
// Shared data and utilities for carousel example
// Supports both fixed-width and variable-width modes via a toggle
// =============================================================================
// Constants
// =============================================================================
export const ITEM_COUNT = 10_000;
export const DEFAULT_HEIGHT = 240;
export const ASPECT_RATIO = 260 / 320; // width / height ≈ 0.8125
// Color palette for cards
export const colors = [
["#667eea", "#764ba2"],
["#f093fb", "#f5576c"],
["#4facfe", "#00f2fe"],
["#43e97b", "#38f9d7"],
["#fa709a", "#fee140"],
["#a18cd1", "#fbc2eb"],
["#fccb90", "#d57eeb"],
["#e0c3fc", "#8ec5fc"],
["#f5576c", "#ff9a9e"],
["#667eea", "#00f2fe"],
];
export const emojis = [
"🎵",
"🎶",
"🎸",
"🥁",
"🎹",
"🎺",
"🎻",
"🎷",
"🪗",
"🪘",
];
export const categories = [
"Photo",
"Video",
"Music",
"Document",
"Archive",
"Code",
"Design",
"Text",
];
export const icons = ["📷", "🎬", "🎵", "📄", "📦", "💻", "🎨", "📝"];
// Width patterns — creates visual variety in variable-width mode
const widthPatterns = [120, 180, 240, 160, 200, 140, 220, 190];
// =============================================================================
// Data Generation
// =============================================================================
// Generate card items (used in both modes)
export const items = Array.from({ length: ITEM_COUNT }, (_, i) => {
const color = colors[i % colors.length];
const categoryIndex = i % categories.length;
// Variable-width fields
const baseWidth = widthPatterns[i % widthPatterns.length];
const isFeatured = i % 17 === 0;
const variableWidth = isFeatured ? baseWidth + 100 : baseWidth;
return {
id: i + 1,
title: `Card ${i + 1}`,
subtitle: `Item #${(i + 1).toLocaleString()}`,
emoji: emojis[i % emojis.length],
gradientStart: color[0],
gradientEnd: color[1],
// Variable-width extras
category: categories[categoryIndex],
icon: icons[categoryIndex],
width: variableWidth,
isFeatured,
};
});
// =============================================================================
// Templates
// =============================================================================
// Fixed-width card template
const fixedTemplate = (item) => `
<div class="card" style="background: linear-gradient(135deg, ${item.gradientStart} 0%, ${item.gradientEnd} 100%);">
<div class="card-emoji">${item.emoji}</div>
<div class="card-title">${item.title}</div>
<div class="card-subtitle">${item.subtitle}</div>
</div>
`;
// Variable-width card template
const variableTemplate = (item) => {
const featuredClass = item.isFeatured ? " card--featured" : "";
return `
<div class="card${featuredClass}" style="background: linear-gradient(135deg, ${item.gradientStart} 0%, ${item.gradientEnd} 100%);">
<div class="card-emoji">${item.icon}</div>
<div class="card-content">
<div class="card-title">${item.isFeatured ? `⭐ Featured #${item.id}` : item.title}</div>
<div class="card-category">${item.category}</div>
<div class="card-width">${item.width}px</div>
</div>
${item.isFeatured ? '<div class="card-badge">Featured</div>' : ""}
</div>
`;
};
// Returns the correct template for the current mode
export function getTemplate(variableWidth) {
return variableWidth ? variableTemplate : fixedTemplate;
}
// =============================================================================
// Config builder
// =============================================================================
// Build vlist config for the given mode, height, and gap.
// Gap is added to item dimensions so vlist spaces items correctly.
export function buildConfig(variableWidth, height = DEFAULT_HEIGHT, gap = 0) {
const cardWidth = Math.round(height * ASPECT_RATIO);
return {
orientation: "horizontal",
scroll: { wheel: true },
ariaLabel: "Horizontal card carousel",
item: {
height,
width: variableWidth
? (index) => items[index].width + gap
: cardWidth + gap,
template: getTemplate(variableWidth),
},
items,
};
}
// =============================================================================
// Utilities
// =============================================================================
// Calculate stats
export function calculateStats(domNodes, total, variableWidth) {
const saved = Math.round((1 - domNodes / total) * 100);
if (variableWidth) {
const widths = items.map((item) => item.width);
const minWidth = Math.min(...widths);
const maxWidth = Math.max(...widths);
const avgWidth = Math.round(
widths.reduce((a, b) => a + b, 0) / widths.length,
);
return { saved, minWidth, maxWidth, avgWidth };
}
return { saved };
}
// Detail panel HTML
export function getDetailHtml(item, index, variableWidth) {
return `
<div class="detail-card" style="background: linear-gradient(135deg, ${item.gradientStart} 0%, ${item.gradientEnd} 100%);">
<div class="detail-card__emoji">${variableWidth ? item.icon : item.emoji}</div>
<div class="detail-card__title">${item.title}</div>
</div>
<div class="detail-meta">
<strong>${item.title}</strong>
<span>Index ${index}${variableWidth ? ` · ${item.category} · ${item.width}px` : ` · ${item.subtitle}`}</span>
${item.isFeatured && variableWidth ? '<span class="detail-meta__badge">⭐ Featured</span>' : ""}
</div>
`;
}
// Format stats HTML
export function formatStatsHtml(domNodes, total, variableWidth) {
const stats = calculateStats(domNodes, total, variableWidth);
let html = `
<span><strong>Total:</strong> ${total.toLocaleString()} items</span>
<span><strong>DOM nodes:</strong> ${domNodes}</span>
<span><strong>Memory saved:</strong> ${stats.saved}%</span>
`;
if (variableWidth && stats.minWidth != null) {
html += `<span><strong>Width:</strong> ${stats.minWidth}–${stats.maxWidth}px (avg ${stats.avgWidth}px)</span>`;
}
return html;
}
/* Carousel Example — example-specific styles only
Common styles (.container, h1, .description, .stats, footer, .split-*, .panel-*)
are provided by example/example.css using shell.css design tokens. */
/* Center the list vertically in the split-main */
.split-main {
display: flex;
align-items: center;
justify-content: center;
height: 560px;
}
/* List container - full width, height set by JS
--card-scale is set by JS (0–1) based on slider height
--item-gap is set by JS (px) from the gap chips */
#list-container {
--card-scale: 1;
--item-gap: 8px;
--item-radius: 12px;
width: 100%;
max-width: 100%;
min-width: 0;
height: auto;
overflow: hidden;
border-radius: var(--item-radius);
}
/* Override vlist defaults for horizontal cards */
#list-container .vlist {
border: none !important;
border-radius: var(--item-radius) !important;
background: transparent;
max-width: 100%;
width: 100%;
box-sizing: border-box;
}
#list-container .vlist-viewport {
max-width: 100%;
width: 100% !important;
}
#list-container .vlist-item {
padding: 0 calc(var(--item-gap) / 2) !important;
border: none !important;
cursor: pointer;
background-color: transparent;
}
/* ============================================================================
Card
============================================================================ */
.card {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: calc(4px + 6px * var(--card-scale));
width: 100%;
height: 100%;
border-radius: var(--item-radius);
color: #fff;
text-align: center;
padding: calc(8px + 12px * var(--card-scale))
calc(6px + 8px * var(--card-scale));
position: relative;
transition: box-shadow 0.15s ease-out;
}
.vlist-item:hover .card {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}
/* Featured cards — variable-width mode */
.card--featured {
border: 2px solid rgba(255, 255, 255, 0.3);
}
.card-emoji {
font-size: 42px;
line-height: 1;
margin-bottom: 16px;
}
.card-content {
display: flex;
flex-direction: column;
gap: 4px;
width: 100%;
}
.card-title {
font-weight: 600;
font-size: calc(11px + 5px * var(--card-scale));
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.card-subtitle {
font-size: calc(10px + 3px * var(--card-scale));
opacity: 0.85;
white-space: nowrap;
}
.card-category {
font-size: calc(9px + 3px * var(--card-scale));
opacity: 0.85;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.card-width {
font-size: calc(8px + 3px * var(--card-scale));
opacity: 0.7;
font-family: monospace;
}
.card-badge {
position: absolute;
top: 6px;
right: 6px;
background: rgba(255, 255, 255, 0.25);
backdrop-filter: blur(4px);
padding: 2px 6px;
border-radius: 10px;
font-size: 8px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
line-height: 1.4;
}
/* ============================================================================
Gap chip buttons
============================================================================ */
.ctrl-btn {
padding: 6px 14px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg-card);
color: var(--text-muted);
font-size: 13px;
font-weight: 600;
font-family: inherit;
cursor: pointer;
transition: all 0.15s ease;
min-width: 36px;
text-align: center;
}
.ctrl-btn:hover {
border-color: var(--accent);
color: var(--accent-text);
}
.ctrl-btn--active {
background: var(--accent);
color: white;
border-color: var(--accent);
}
/* ============================================================================
Toggle switch
============================================================================ */
.toggle {
display: flex;
align-items: center;
cursor: pointer;
user-select: none;
}
.toggle input {
display: none;
}
.toggle-track {
position: relative;
width: 36px;
height: 20px;
border-radius: 10px;
background: var(--border);
transition: background 0.2s ease;
flex-shrink: 0;
}
.toggle input:checked + .toggle-track {
background: var(--accent, #667eea);
}
.toggle-track::after {
content: "";
position: absolute;
top: 2px;
left: 2px;
width: 16px;
height: 16px;
border-radius: 50%;
background: #fff;
transition: transform 0.2s ease;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
.toggle input:checked + .toggle-track::after {
transform: translateX(16px);
}
/* ============================================================================
Card Detail (panel preview)
============================================================================ */
.detail-card {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
height: 120px;
border-radius: 10px;
color: #fff;
text-align: center;
padding: 16px 12px;
margin-bottom: 8px;
}
.detail-card__emoji {
font-size: 32px;
line-height: 1;
}
.detail-card__title {
font-weight: 600;
font-size: 14px;
}
.detail-meta {
display: flex;
flex-direction: column;
gap: 2px;
font-size: 13px;
}
.detail-meta strong {
font-weight: 600;
}
.detail-meta span {
font-size: 12px;
color: var(--text-muted);
}
.detail-meta__badge {
font-size: 11px;
color: var(--accent, #667eea);
font-weight: 600;
}