Here’s an example of how to implement the ripple effect on a button in JavaScript:
HTML:
php code<button class="btn">Click me</button>
CSS:
cssCopy code.btn {
position: relative;
display: inline-block;
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
background-color: lightblue;
color: white;
cursor: pointer;
}
.ripple {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: inherit;
background-color: rgba(255, 255, 255, 0.3);
transform: scale(0);
pointer-events: none;
}
JavaScript:
javascript codeconst btn = document.querySelector('.btn');
btn.addEventListener('click', function(event) {
const ripple = document.createElement('div');
ripple.classList.add('ripple');
btn.appendChild(ripple);
const rect = btn.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
ripple.style.left = `${x}px`;
ripple.style.top = `${y}px`;
ripple.style.transform = 'scale(1)';
setTimeout(() => {
ripple.remove();
}, 500);
});
This code creates a ripple effect when the button is clicked. When the button is clicked, a div
element with class “ripple” is created and appended to the button. The position of the ripple is set based on the click event’s x and y coordinates relative to the button’s position. The ripple is then animated by setting its transform property to scale(1)
, creating the appearance of it spreading out from the point of the click. Finally, the ripple is removed after 500 milliseconds using the setTimeout
function.