JSFiddle - React, Tailwind, and code Playground

by jschr

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
<textarea></textarea>
<div class="container" />

CSS

textarea {
  height: 100px;
  width: 400px;
}

.container {
  height: 100px;
  width: 400px;
  margin-top: 10px;
  background: #f0f0f0;
}

JavaScript

const textarea = document.querySelector('textarea')
const container = document.querySelector('.container')

const createSpan = (char) => {
  const span = document.createElement('span')
  span.classList.add('fadeIn')
  span.classList.add('animated')
  span.innerText = char
  return span
}

const updateChars = () => {
  const updatedChars = []
  const currentSpans = Array.from(container.querySelectorAll('span'))
  const chars = textarea.value.split('')
  // Iterate over each character in the textarea and append 
  // new chars to the container.
  chars.forEach((char, index) => {
    const spanAtIndex = currentSpans[index]
    // Add new span if one doesn't exist at current index
    if (!spanAtIndex) {
      container.appendChild(createSpan(char))
    }
    // TODO: Handle deletions
  })
}

textarea.addEventListener('keypress', () => {
  setTimeout(updateChars)
}, false)