Back
Explore the art of creating an interactive button with a captivating ripple effect to enhance your web interface.
<div class="button-container"> <button class="ripple-button" onclick="createRipple(event)">Click Me</button> </div>
.button-container {The ripple class styles the span that we'll dynamically add to our button on click. Notice how it scales up and fades out, achieving the ripple effect:
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.ripple-button {
position: relative;
overflow: hidden;
border: none;
padding: 15px 30px;
font-size: 16px;
color: #ffffff;
background-color: #6200ea;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.3s;
}
.ripple-button:hover {
background-color: #3700b3;
}
.ripple {
position: absolute;
border-radius: 50%;
background: rgba(255, 255, 255, 0.6);
transform: scale(0);
animation: ripple-animation 0.6s linear;
}
@keyframes ripple-animation {
to {
transform: scale(4);
opacity: 0;
}
}
function createRipple(event) {
const button = event.currentTarget;
const circle = document.createElement('span');
const diameter = Math.max(button.clientWidth, button.clientHeight);
const radius = diameter / 2;
circle.style.width = circle.style.height = `${diameter}px`;
circle.style.left = `${event.clientX - button.offsetLeft - radius}px`;
circle.style.top = `${event.clientY - button.offsetTop - radius}px`;
circle.classList.add('ripple');
const ripple = button.getElementsByClassName('ripple')[0];
if (ripple) {
ripple.remove();
}
button.appendChild(circle);
}
<div class="button-container"> <button class="ripple-button" onclick="createRipple(event)">Click Me</button> </div> <script> function createRipple(event) { const button = event.currentTarget; const circle = document.createElement('span'); const diameter = Math.max(button.clientWidth, button.clientHeight); const radius = diameter / 2; circle.style.width = circle.style.height = `${diameter}px`; circle.style.left = `${event.clientX - button.offsetLeft - radius}px`; circle.style.top = `${event.clientY - button.offsetTop - radius}px`; circle.classList.add('ripple'); const ripple = button.getElementsByClassName('ripple')[0]; if (ripple) { ripple.remove(); } button.appendChild(circle); } </script> <style> .button-container { display: flex; justify-content: center; align-items: center; height: 100vh; } .ripple-button { position: relative; overflow: hidden; border: none; padding: 15px 30px; font-size: 16px; color: #ffffff; background-color: #6200ea; cursor: pointer; border-radius: 5px; transition: background-color 0.3s; } .ripple-button:hover { background-color: #3700b3; } .ripple { position: absolute; border-radius: 50%; background: rgba(255, 255, 255, 0.6); transform: scale(0); animation: ripple-animation 0.6s linear; } @keyframes ripple-animation { to { transform: scale(4); opacity: 0; } } </style>Thank you for reading this article.
Comments
No comments yet. Be the first to comment!