How do I add a ripple effect when a button is pressed?
A ripple gives instant feedback and shows exactly where the user pressed. We add a round element at the press point and scale and fade it with CSS, with one line of JavaScript to find the position.
Steps
- Give the button position: relative and overflow: hidden so the ripple stays inside.
- On click, compute the press point relative to the button with getBoundingClientRect().
- Create a round span with a diameter that covers the whole button and center it on the press point.
- Animate the span with transform: scale and opacity only (fast, no layout work), then remove it on animationend.
- For a keyboard press (coordinates are 0) start the ripple at the button center. With reduced motion, create no ripple. RTL does not matter because the math uses screen coordinates.
The code
HTML
<!doctype html>
<html lang="ar" dir="rtl">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Button Ripple</title>
<style>
body { min-height: 100vh; display: grid; place-items: center; margin: 0; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; }
.ripple-btn { position: relative; overflow: hidden; padding: .8rem 1.8rem; border: 0; border-radius: .6rem;
background: #6c5ce7; color: #fff; font: inherit; cursor: pointer; }
.ripple-btn:focus-visible { outline: 3px solid #fdcb6e; outline-offset: 2px; }
.ripple { position: absolute; border-radius: 50%; background: rgba(255,255,255,.45);
transform: scale(0); opacity: 1; pointer-events: none; animation: ripple .6s ease-out forwards; }
@keyframes ripple { to { transform: scale(1); opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .ripple { display: none; } }
</style>
<button class="ripple-btn" type="button">احجز الآن</button>
<script>
document.querySelectorAll(".ripple-btn").forEach((btn) => {
btn.addEventListener("click", (e) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const r = btn.getBoundingClientRect();
const keyboard = e.clientX === 0 && e.clientY === 0;
const x = keyboard ? r.width / 2 : e.clientX - r.left;
const y = keyboard ? r.height / 2 : e.clientY - r.top;
const d = Math.hypot(r.width, r.height) * 2; // big enough to cover the button
const s = document.createElement("span");
s.className = "ripple";
s.style.cssText = `width:${d}px;height:${d}px;left:${x - d / 2}px;top:${y - d / 2}px`;
s.addEventListener("animationend", () => s.remove());
btn.appendChild(s);
});
});
</script>
</html>