How to create a Ripple Effect on Click the Button ?
The ripple effect is a part of the modern design trend. You have seen it on many websites specially on Google’s material design language. It gives a button-pressing effect. We can make a ripple effect by adding and animating a child element to the button. We can also position it according to the position of the cursor on the button using Javascript.
Basic styling: Add basic styling to the button with a position: relative attribute to position the inner span tag and overflow: hidden to prevent span from going outside of the button.
Add styling to the span element: Now add the style for the span element that will show up on the click of a button.
Adding JavaScript: Now we’ll add the span element on the button click with position according to the mouse click. On button click we have to do the following:
- Create a span element and add a ripple class to it.
- Get the clicked position of the cursor using the event variable.
- Set the position of the span element.
- Remove the span element to avoid spamming of span elements in the button.
Example:
html
<!DOCTYPE html>
< html >
< head >
< title >
Button Ripple Effect - GFG
</ title >
< style >
/* Adding styles to button */
.btn {
padding: 12px 50px;
border: none;
border-radius: 5px;
background-color: #1abc9c;
color: #fff;
font-size: 18px;
outline: none;
cursor: pointer;
/* We need this to position
span inside button */
position: relative;
overflow: hidden;
box-shadow: 6px 7px 40px -4px
rgba(0, 0, 0, 0.2);
}
</ style >
</ head >
< body >
< button class = "btn" >
Enter GeeksforGeeks
</ button >
</ body >
</ html >
|
CSS
<style>
.btn span {
position : absolute ;
border-radius: 50% ;
background-color : rgba( 0 , 0 , 0 , 0.3 );
width : 100px ;
height : 100px ;
margin-top : -50px ;
margin-left : -50px ;
animation: ripple 1 s;
opacity: 0 ;
}
@keyframes ripple {
from {
opacity: 1 ;
transform: scale( 0 );
}
to {
opacity: 0 ;
transform: scale( 10 );
}
}
</style>
|
Javascript
<script>
const btn = document.querySelector( ".btn" );
btn.onclick = function (e) {
let ripple = document.createElement( "span" );
ripple.classList.add( "ripple" );
this .appendChild(ripple);
let x = e.clientX - e.target.offsetLeft;
let y = e.clientY - e.target.offsetTop;
ripple.style.left = `${x}px`;
ripple.style.top = `${y}px`;
setTimeout(() => {
ripple.remove();
}, 300);
};
</script>
|
Output: Click here to check the live Output.
Last Updated :
07 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...