I am trying to add a material ripple effect to an element using pure javascript using the code below. The problem is that the effect works only for the first click.
If I try to click the button again, I get the message Uncaught TypeError: circle is undefined on my console.
function createRipple(event) {
const target = event.currentTarget;
const circle = target.classList.add("ripple");
const ripple = circle.getElementsByClassName("ripple")[0];
if (ripple) {
ripple.remove();
}
}
const buttons = document.getElementsByClassName("my-ripple");
for (const button of buttons) {
button.addEventListener("click", createRipple);
}
.my-ripple {
position: relative;
overflow: hidden;
display: inline-block;
width: auto;
padding: 1.2rem;
font-family: sans;
cursor: pointer;
border-radius: 10px;
}
.ripple::after {
content: "";
position: absolute;
border-radius: 50%;
transform: scale(0);
animation: ripple 600ms linear;
background-color: rgba(0, 0, 0, 0.5);
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
}
@keyframes ripple {
to {
transform: scale(4);
opacity: 0;
}
}
<div class="my-ripple">Click me</div>