JS Problems geeksforgeeks Exercises and Solutions for Beginners

How to Cycle Through Text in JavaScript and CSS 📌[All Method]️

It’s also a question How to Cycle Through Text in JavaScript and CSS? If you get stuck or have questions at any point,simply comment below.
Question: What is the best solution for this problem? Answer: This blog code can help you solve errors How to Cycle Through Text in JavaScript and CSS. Question: What are the reasons for this code mistake and how can it be fixed? Answer: You can find a solution by following the advice in this blog.

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;
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.

Now you learned, How you can use & How to Cycle Through Text in JavaScript and CSS.
If you have any questions or get stuck, please dont hesitate to reach out to me for help.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button