How to Cycle Through Text in JavaScript and CSS


I was building an application for a client that needed text that was constantly changing in a loop.

Suppose we have a <span> element that will hold the text.

<span id="cycle"></span>

We want the text in this <span> to cycle through this array of words.

const textList = ["Corgi", "Shih Tzu", "Pug", "Dachshund"];

I found that we can approach this problem both in JavaScript and in CSS.

JavaScript Cycling

Given the text list above, we can cycle through the list in JavaScript like so.

const cycle = document.querySelector("#cycle");
let i = 0;
const cycleText = () => {
  cycle.innerHTML = textList[i];
  i = ++i % textList.length;
};
cycleText();
setInterval(cycleText, 1000);

We call cycleText() every second, updating the current index of textList at each iteration.

CSS Cycling

We can use keyframes in CSS to achieve the same result.

#cycle:after {
    -webkit-animation: cycle 4s infinite; /* Safari 4+ */
    -moz-animation: cycle 4s infinite; /* Fx 5+ */
    -o-animation: cycle 4s infinite; /* Opera 12+ */
    animation: cycle 4s infinite; /* IE 10+, Fx 29+ */
  }
}
@keyframes cycle {
  0% {
    content: "Corgi";
  }
  33% {
    content: "Shih Tzu";
  }
  66% {
    content: "Pug";
  }
  100% {
    content: "Dachshund";
  }
}

We’re specifying that we want the keyframe animation to run for four seconds, and we want it to run indefinitely.

In the @keyframes cycle block, in a percentage, we’re specifying when each word should be displayed.