Layout · 20 of 23

Notification Badge

Scale bounce on update

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="badge-container">
  <span>Cart</span>
  <span class="badge" id="cartBadge">0</span>
</div>
<button class="add-btn" id="addBtn">+1</button>

CSS

.badge-container {
  position: relative;
  display: inline-block;
  font-size: 1.2rem;
  color: #f0f0f5;
  margin-right: 1rem;
}

.badge {
  /* em units so the offsets track the label's font-size, keeping the badge clear
     of the cap height instead of overlapping the final glyph */
  position: absolute;
  top: -0.6em;
  right: -1.15em;
  background: #7c5cff;
  color: #fff;
  font-size: 0.7rem;
  font-weight: 600;
  line-height: 1;
  min-width: 1.25rem;
  padding: 0.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 999px;
  /* Ring reads as a floating badge lifted off the label */
  box-shadow: 0 0 0 2px #16161a;
  transform-origin: center;
}

.badge.bump {
  animation: badgeBump 0.3s;
}

@keyframes badgeBump {
  0% { transform: scale(1); }
  50% { transform: scale(1.5); }
  100% { transform: scale(1); }
}

.add-btn {
  padding: 0.25rem 0.75rem;
  background: #333;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

JavaScript

var addBtn = document.getElementById('addBtn');
var badge = document.getElementById('cartBadge');
var count = 0;

addBtn.addEventListener('click', function () {
  count++;
  badge.textContent = count;
  // Remove + reflow + re-add restarts the bump animation every click
  badge.classList.remove('bump');
  void badge.offsetWidth;
  badge.classList.add('bump');
});