Layout · 22 of 23

Odometer

Digits roll like a slot machine

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="odometer" id="odometer"></div>
<button class="trigger-btn" id="odometerBtn">Roll</button>

CSS

.trigger-btn {
  padding: 0.6rem 1.2rem;
  background: #7c5cff;
  color: white;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
}

.odometer {
  display: flex;
  gap: 4px;
}

/* Each digit is a fixed-height window... */
.odo-digit {
  width: 36px;
  height: 52px;
  background: #222;
  border: 1px solid rgba(255, 255, 255, 0.06);
  border-radius: 6px;
  overflow: hidden;
  position: relative;
}

/* ...and a 0-9 strip slides vertically inside it */
.odo-strip {
  display: flex;
  flex-direction: column;
  transition: transform 1.2s cubic-bezier(0.16, 1, 0.3, 1);
}

.odo-strip span {
  height: 52px; /* must match .odo-digit height */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.6rem;
  font-weight: 700;
  font-variant-numeric: tabular-nums;
  color: #7c5cff;
}

JavaScript

var odometer = document.getElementById('odometer');
var odometerBtn = document.getElementById('odometerBtn');
var DIGITS = 4;
var DIGIT_HEIGHT = 52; // px — must match the CSS

// Build one 0-9 strip per digit
var strips = [];
for (var i = 0; i < DIGITS; i++) {
  var digit = document.createElement('div');
  digit.className = 'odo-digit';
  var strip = document.createElement('div');
  strip.className = 'odo-strip';
  for (var n = 0; n <= 9; n++) {
    var s = document.createElement('span');
    s.textContent = n;
    strip.appendChild(s);
  }
  digit.appendChild(strip);
  odometer.appendChild(digit);
  strips.push(strip);
}

// Slide each strip so the right number shows through the window
function rollTo(value) {
  var str = String(value).padStart(DIGITS, '0');
  strips.forEach(function (strip, i) {
    strip.style.transform = 'translateY(-' + ((+str[i]) * DIGIT_HEIGHT) + 'px)';
  });
}

rollTo(0);
odometerBtn.addEventListener('click', function () {
  rollTo(Math.floor(Math.random() * 10000));
});