Alternating text

CSS, Animation · May 25, 2023

Creates an alternating text animation.

  • Create a <span> for the text that will be alternated.
  • Define an animation, alternating-text, that makes the <span> disappear by setting display: none.
  • In JavaScript, define an array of the different words that will be alternated and use the first word to initialize the content of the <span>.
  • Use EventTarget.addEventListener() to define an event listener for the 'animationiteration' event. This will run the event handler whenever an iteration of the animation is completed.
  • Use Element.innerHTML to display the next element in the array as the content of the <span>.
<p>I love coding in <span class="alternating" id="alternating-text"></span>.</p>
.alternating {
  animation-name: alternating-text;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-timing-function: ease;

@keyframes alternating-text {
  90% {
    display: none;
const texts = ['Java', 'Python', 'C', 'C++', 'C#', 'Javascript'];
const element = document.getElementById('alternating-text');

let i = 0;
const listener = e => {
  i = i < texts.length - 1 ? i + 1 : 0;
  element.innerHTML = texts[i];

element.innerHTML = texts[0];
element.addEventListener('animationiteration', listener, false);

More like this

  • Hover underline animation

    Creates an animated underline effect when the user hovers over the text.

    CSS, Animation · Oct 11, 2021

  • Staggered animation

    Creates a staggered animation for the elements of a list.

    CSS, Animation · Oct 11, 2021

  • Typewriter effect

    Creates a typewriter effect animation.

    CSS, Animation · May 24, 2021