How to Cycle Through Text in JavaScript and CSS đ[All Method]ī¸
![How to Cycle Through Text in JavaScript and CSS đ[All Method]ī¸](https://howisguide.com/wp-content/uploads/2022/02/How-to-Cycle-Through-Text-in-JavaScript-and-CSS-All-Method.png)
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;
};
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.
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.