javascripthtmlcssripple-effect

How to confine ripple effect inside button only


I am trying to make ripple effect of button, but my ripple is going out of button as you can see in below given snippet. I even set

overflow : hidden;

still it is going out. Please tell how to confine ripple inside button only.

document.getElementById("btn").addEventListener("mousedown",(e)=>{
var btn = document.getElementById("btn")
var ripple = document.createElement("span")
            ripple.classList.add("ripple")
            btn.appendChild(ripple)
            ripple.style.animation = "ripple 500ms linear forwards"
            ripple.style.top = e.clientY - 15 + "px";
            ripple.style.left = e.clientX - 15 + "px";
            setTimeout(()=>{
              ripple.remove()
            },500)

})
.modaljs-btn-green {
    /* position: relative; */
    padding: 10px;
    font-size: 15px;
    color: #28b32f;
    font-weight: 600;
    border: none;
    outline: none;
    border-radius: 2px;
    transition: all 325ms;
    cursor: pointer;
    margin-left: 10px;
    overflow: hidden;
}
.modaljs-btn-green:hover {
    background-color: rgb(198, 255, 196);
}

.ripple{
    border-radius: 50%;
    position: absolute;
    background-color: grey;
    width: 50px;
    height: 50px;
    opacity: 0.5;
}

@keyframes ripple{
    0%{
        transform: scale(0);
        opacity: 0.5;
    }
    100%{
        transform: scale(3);
        opacity: 0;
    }
}
<button id="btn" class="modaljs-btn-green">LOGIN</button>


Solution

  • Try adding position: relative; to the .modaljs-btn-green class

    document.getElementById("btn").addEventListener("mousedown",(e)=>{
    var btn = document.getElementById("btn")
    var ripple = document.createElement("span")
                ripple.classList.add("ripple")
                btn.appendChild(ripple)
                ripple.style.animation = "ripple 500ms linear forwards"
                ripple.style.top = e.clientY - 15 + "px";
                ripple.style.left = e.clientX - 15 + "px";
                setTimeout(()=>{
                  ripple.remove()
                },500)
    
    })
    .modaljs-btn-green {
        position: relative;
        padding: 10px;
        font-size: 15px;
        color: #28b32f;
        font-weight: 600;
        border: none;
        outline: none;
        border-radius: 2px;
        transition: all 325ms;
        cursor: pointer;
        margin-left: 10px;
        overflow: hidden;
    }
    .modaljs-btn-green:hover {
        background-color: rgb(198, 255, 196);
    }
    
    .ripple{
        border-radius: 50%;
        position: absolute;
        background-color: grey;
        width: 50px;
        height: 50px;
        opacity: 0.5;
    }
    
    @keyframes ripple{
        0%{
            transform: scale(0);
            opacity: 0.5;
        }
        100%{
            transform: scale(3);
            opacity: 0;
        }
    }
    <button id="btn" class="modaljs-btn-green">LOGIN</button>