본문 바로가기

Frontend/JavaScript

JavaScript Module - Button Ripple Effect

반응형

Let's see how we can create a button ripple effect. The completed code looks like the one below. I have used the coordinates and the click event to implement this.

// wave-module.js

export function createEffect() {
  const btn = document.querySelector('button')
  const rippleEl = document.querySelector('.ripple')

  btn.addEventListener('click', (e) => {
    rippleEl.classList.add('clicked')
    rippleEl.style.left = `${e.clientX - e.target.getBoundingClientRect().x}px`
    rippleEl.style.top = `${e.clientY - e.target.getBoundingClientRect().y}px`
    setTimeout(() => {
      rippleEl.classList.remove('clicked')
    }, 1500)
  })
}

Configuration

First, add the attribute below to your main JavaScript file so that we can use modules

type="module"
<!-- 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>Document</title>

  <!-- custom style -->
  <link rel="stylesheet" href="main.css" />
  <script defer type="module" src="index.js"></script>
</head>

<body>
  <button>Click
    <div class="ripple"></div>
  </button>
</body>

</html>

Add styles to your CSS file or add another style

 

/* module.css */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  height: 100vh;
  background-color: #3c3232;
  display: flex;
  align-items: center;
  justify-content: center;
}

button {
  height: 70px;
  width: 150px;
  border-radius: 5px;
  background-color: rgb(226, 43, 177);
  color: aliceblue;
  position: relative;
  overflow: hidden;
}

.ripple {
  height: 50px;
  width: 50px;
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  animation: widen 1.5s ease forwards;
  background-color: rgba(255, 255, 255, .4);  
}

.ripple.clicked {
  display: initial;
}

@keyframes widen {
  0% {
    transform: translate(-50%, -50%) scale(0);
  }

  80% {
    transform: translate(-50%, -50%) scale(1);
  }

  100% {
    opacity: 0;
  }
}

Finally, import the function and call it

 

// index.js

import { createEffect } from "./module.js";

createEffect()

I have shown you how to make a button ripple effect and how to use a module to easily implement the feature. I hope this is helpful

 

 

728x90
반응형

'Frontend > JavaScript' 카테고리의 다른 글

Canvas  (0) 2023.07.11
Drag and Drop  (1) 2023.07.05
NPM - JSON Server  (0) 2023.05.22
JavaScript Module - Text Wave Effect  (2) 2023.04.05
Client Side Storage - Indexed DB  (0) 2023.03.31