Home Code Snippets Button Ripple Effect

Button Ripple Effect

Aug 3, 2022
Button Ripple Effect using HTML, CSS & JAVASCRIPT
Live Preview

index.html

<!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">
        <title>Ripple Button Effect</title>
        <link rel="stylesheet" href="style.css">
    </head>

    <body>
        <div class="btn-div">

            <button>Button</button>
        </div>

        <script src="main.js"></script>

    </body>

</html>

style.css

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400&display=swap');

body {
    background-color: #efefef;
    font-family: 'Poppins', sans-serif;
}

button {
    font-size: 18px;
    padding: 0.8em 1.7em;
    margin: 2px;
    border: 0;
    outline: 0;
    color: white;
    background-color: #2196f3;
    text-transform: uppercase;
    border-radius: 0.15em;
    box-shadow: 0 0 8px rgb(0 0 0 / 30%);
    position: relative;
    overflow: hidden;
    cursor: pointer;
}

button .ripple {
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.7);
    position: absolute;
    transform: scale(0);
    animation: ripple 0.6s linear;
}


@keyframes ripple {
    to {
        transform: scale(2.5);
        opacity: 0;
    }
}

main.js

var buttons = document.getElementsByTagName('button');

Array.prototype.forEach.call(buttons, function(b){
  b.addEventListener('click', createRipple);
})

function createRipple(e)
{
  if(this.getElementsByClassName('ripple').length > 0)
    {
      this.removeChild(this.childNodes[1]);
    }
  
  var circle = document.createElement('div');
  this.appendChild(circle);
  
  var d = Math.max(this.clientWidth, this.clientHeight);
  circle.style.width = circle.style.height = d + 'px';
  
  circle.style.left = e.clientX - this.offsetLeft - d / 2 + 'px';
  circle.style.top = e.clientY - this.offsetTop - d / 2 + 'px';
  
  circle.classList.add('ripple');
}
Share this snippet: