Typography · 33 of 33

Gravity Drop

Click — letters fall with gravity and bounce. Click again to reset

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="gravity-wrapper" id="gravityWrapper">
  <p class="gravity-headline" id="gravityHeadline"></p>
</div>

CSS

.gravity-wrapper {
  min-height: 160px;
  cursor: pointer;
  overflow: hidden;
}

.gravity-headline {
  display: flex;
  justify-content: center;
  font-size: 3.5rem;
  font-weight: 600;
}

.gravity-char {
  display: inline-block;
  will-change: transform;
}

JavaScript

var headline = document.getElementById('gravityHeadline');
var wrapper = document.getElementById('gravityWrapper');
var text = 'Timber!';

headline.innerHTML = text.split('').map(function (c) {
  return '<span class="gravity-char">' + c + '</span>';
}).join('');
var chars = headline.querySelectorAll('.gravity-char');

var dropped = false;
var rafId = null;

function drop() {
  var wrapRect = wrapper.getBoundingClientRect();
  var bodies = Array.from(chars).map(function (el) {
    var r = el.getBoundingClientRect();
    return {
      el: el,
      y: 0,
      vy: -(2 + Math.random() * 3),        // small upward pop first
      rot: 0,
      vr: (Math.random() - 0.5) * 10,
      floor: wrapRect.bottom - r.bottom,   // distance to wrapper floor
      delay: Math.random() * 15,           // frames before falling
      bounces: 0
    };
  });

  function tick() {
    var alive = false;
    bodies.forEach(function (b) {
      if (b.delay > 0) { b.delay--; alive = true; return; }
      b.vy += 0.9;                         // gravity
      b.y += b.vy;
      b.rot += b.vr;
      if (b.y >= b.floor) {
        b.y = b.floor;
        b.vy *= -0.45;                     // restitution
        b.vr *= 0.6;
        b.bounces++;
        if (Math.abs(b.vy) < 1 || b.bounces > 4) { b.vy = 0; b.vr = 0; }
      }
      if (b.vy !== 0 || b.y < b.floor) alive = true;
      b.el.style.transform = 'translateY(' + b.y + 'px) rotate(' + b.rot + 'deg)';
    });
    if (alive) rafId = requestAnimationFrame(tick);
  }
  rafId = requestAnimationFrame(tick);
}

function reset() {
  if (rafId) cancelAnimationFrame(rafId);
  chars.forEach(function (el) {
    el.style.transition = 'transform 0.5s cubic-bezier(0.16, 1, 0.3, 1)';
    el.style.transform = 'translateY(0) rotate(0deg)';
    setTimeout(function () { el.style.transition = ''; }, 500);
  });
}

wrapper.addEventListener('click', function () {
  dropped = !dropped;
  if (dropped) drop(); else reset();
});