Stop animation from repeating for dynamically added JavaScript

ashima panjwani :

I'm trying to create a typing animation in which each word is dynamically added using javascript. Once it gets added I want its opacity to change from 0 to 1 for which I have added the class typing-opacity.

let content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.';

let elem = content.split(' ');
let container = document.getElementById('chatMsg');
for (let i = 0; i < elem.length; i++) {
  setTimeout(function() {
    container.innerHTML += '<span class="typing-opacity">' + elem[i] + ' </span>';
  }, 250 * i)
}
.typing-opacity {
  animation: opacity 0.25s;
}

@keyframes opacity {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<div id='chatMsg'></div>

The problem I'm facing is that all the span animations are getting repeated every time I add a new word to the paragraph. I want the animation to only get called once at the initial insertion of the word and not every time. How do I prevent the animations from getting called each time?

NOTE: Please do not suggest solutions involving JQuery or other libraries. I have to implement this using vanilla JS

Batu.Khan :

How about deleting previous span tags before adding new ones?

let content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.';

let elem = content.split(' ');
let container = document.getElementById('chatMsg');
for (let i = 0; i < elem.length; i++) {
  setTimeout(function() {
    container.innerHTML = container.innerHTML.replace(/<span class="typing-opacity">/g, '').replace(/<\/span>/g, '');
    container.innerHTML += '<span class="typing-opacity">' + elem[i] + ' </span>';
  }, 250 * i)
}
.typing-opacity {
  animation: opacity 0.25s;
}

@keyframes opacity {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<div id='chatMsg'></div>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=34475&siteId=1