본문 바로가기

Frontend/JavaScript

JavaScript Module - Text Wave Effect

반응형

Let's see how we can create a wave effect. The completed code looks like the one below. To make it easy to implement this feature to any existing website, I structured this to work by adding a class name to a text element. When you add the class name 'wave-text', the effect will take effect given that you have done the necessary configurations.

// wave-module.js

const waveTextEl = document.querySelector('.wave-text')

setInterval(() => {
  const child = waveTextEl.firstElementChild
  const spanEls = document.querySelectorAll('.wave-text span')

  if (window.getComputedStyle(child).transform.includes('-40')) {
    spanEls.forEach(span => {
      span.classList.remove('up')
    });
  } else {
    spanEls.forEach(span => {
      span.classList.add('up')
    });
  }
}, 2000)

export function createSpans() {
  waveTextEl.innerHTML = waveTextEl.innerText.split('').map((p, idx) => `<span style="transition-delay: ${idx * 50}ms">${(p === ' ' ? '&nbsp;' : p)}</span>`).join('')
}

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>
  <h2 class="wave-text">wave effect</h2>
</body>

</html>

Add styles to your CSS file or add another style

/* module.css */

.wave-text span {
  display: inline-block;
  transition: 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55);
  transform: translateY(-0px);
}

.wave-text span.up {
  transform: translateY(-40px);
}

Finally, import the function and call it

// index.js

import { createSpans } from "./wave-module.js";

createSpans()

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

 

728x90
반응형

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

JavaScript Module - Button Ripple Effect  (1) 2023.07.03
NPM - JSON Server  (0) 2023.05.22
Client Side Storage - Indexed DB  (0) 2023.03.31
Client Side Storage - Web Storage  (0) 2023.03.31
Module System  (0) 2023.03.29