Skip to content

Instantly share code, notes, and snippets.

@Posandu
Created April 29, 2022 14:32
Show Gist options
  • Save Posandu/1ad5a7e5bafcd1d68c9339ce40c10fc0 to your computer and use it in GitHub Desktop.
Save Posandu/1ad5a7e5bafcd1d68c9339ce40c10fc0 to your computer and use it in GitHub Desktop.
Ripple
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
padding: 100px;
background-color: #2b3438;
}
.btn {
background: #37474f;
border: none;
padding: 10px 16px;
font-family: system-ui;
border-radius: 4px;
color: white;
font-weight: 400;
position: relative;
overflow: hidden;
transition: all 0.2s ease;
}
.btn:hover {
background: #3f51b5;
}
.btn:active {
box-shadow: -2px 2px 2px rgba(0, 0, 0, 0.2);
}
.ripple {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.151);
transform: scale(0);
animation: ripple 0.6s cubic-bezier(0.075, 0.82, 0.165, 1) forwards;
pointer-events: none;
transition: all 0.2s ease;
}
@keyframes ripple {
0% {
transform: scale(0);
}
100% {
transform: scale(1);
}
}
</style>
</head>
<body>
<button class="btn">
Button
</button>
<script>
const btn = document.querySelector('.btn');
const attachRipple = element => {
let circle;
let rippling = false;
const findFurthestPoint = (clickPointX, elementWidth, offsetX, clickPointY, elementHeight, offsetY) => {
const x = clickPointX - offsetX > elementWidth / 2 ? 0 : elementWidth;
const y = clickPointY - offsetY > elementHeight / 2 ? 0 : elementHeight;
const d = Math.hypot(x - (clickPointX - offsetX), y - (clickPointY - offsetY));
return d;
}
element.onpointerdown = (e) => {
if (rippling) return;
rippling = true;
const rect = e.target.getBoundingClientRect();
const radius = findFurthestPoint(e.clientX, e.target.offsetWidth, rect.left, e.clientY, e.target.offsetHeight, rect.top);
circle = document.createElement("div");
circle.classList.add("ripple");
circle.style.left = e.clientX - rect.left - radius + "px";
circle.style.top = e.clientY - rect.top - radius + "px";
circle.style.width = circle.style.height = radius * 2 + "px";
e.target.appendChild(circle);
}
"pointerup mouseleave dragleave touchmove touchend touchcancel".split(" ").forEach(event => {
element.addEventListener(event, () => {
if (circle) {
// Remove ripple after animation is finished
setTimeout(() => {
circle.style.opacity = 0;
rippling = false;
}, 200);
}
});
});
}
attachRipple(btn);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment