JSFiddle - React, Tailwind, and code Playground

by HDL52

HTML

<section class="typing-container">
  <p>
    I LOVE 
    <span class="typing-text"></span>
  </p>
</section>

CSS

@import url(https://fonts.googleapis.com/css?family=VT323);

* {
  margin: 0;
  padding: 0;
}

body {
  font-family: VT323, sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #000;
}

.typing-container {
  width: 100%;
  display: flex;
  text-align: center;
  justify-content: center;
  color: whitesmoke;
  font-size: 2rem;
}

.typing-text {
  color: white;
}

.typing-text::after {
  content: "|";
  animation: blink 1s step-end infinite;
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }
}

@media screen and (max-width: 768px) {
  .typing-container {
    font-size: 1.5rem;
  }
}

JavaScript

const text = document.querySelector('.typing-text');
const words = ["Basketball...", "Tennis...", "Volleyball..."];

const initializeTypingEffect = (element, wordsArray) => {
  const LETTER_TYPE_DELAY = 75;
  const WORD_STAY_DELAY = 2000;

  const DIRECTION_FORWARDS = 0;
  const DIRECTION_BACKWARDS = 1;

  let direction = DIRECTION_FORWARDS;
  let wordIndex = 0;
  let letterIndex = 0;
  let typingInterval;

  const startTyping = () => {
    typingInterval = setInterval(typeLetter, LETTER_TYPE_DELAY);
  };

  const typeLetter = () => {
    const currentWord = wordsArray[wordIndex];

    if (direction === DIRECTION_FORWARDS) {
      letterIndex++;

      if (letterIndex === currentWord.length) {
        direction = DIRECTION_BACKWARDS;
        clearInterval(typingInterval);
        setTimeout(startTyping, WORD_STAY_DELAY);
      }
    } else if (direction === DIRECTION_BACKWARDS) {
      letterIndex--;

      if (letterIndex === 0) {
        moveToNextWord();
      }
    }

    const textToType = currentWord.substring(0, letterIndex);
    element.textContent = textToType;
  };

  const moveToNextWord = () => {
    letterIndex = 0;
    direction = DIRECTION_FORWARDS;
    wordIndex++;

    if (wordIndex === wordsArray.length) {
      wordIndex = 0;
    }
  };

  startTyping();
};

initializeTypingEffect(text, words);