Reputation: 403
I have some words like "beautiful","awesome","nice" and "wonderful".
i want to show the each word as typing text effect one after one for infinite time.
see i want like this :google forms
I have made the running text effect. see the code below:
var myText= "beautiful";
var text = myText.split("");
var counter = 0;
function typeIt(text){
var SI=setInterval(function(){
var h1 = $("#myTypingText");
h1.append(text[counter]);
counter++;
if(counter==text.length){
clearInterval(SI);
}
},70);
}
i am not able to run this function for each word one after one for infinite time.
please help me to resolve this.
thanks in advance.
Upvotes: 1
Views: 2048
Reputation: 150030
You can modify your existing function to accept an array of words, and process the words one by one.
EDIT: Expand this first snippet to see my original answer that has no delay in between words:
function typeIt(words) {
var letterIndex = 0;
var wordIndex= 0;
var h1 = $("#myTypingText");
var SI = setInterval(function() {
if (letterIndex === words[wordIndex].length) { // if at end of current word
wordIndex = (wordIndex + 1) % words.length; // go to next word
letterIndex = 0;
h1.empty(); // clear output div
}
h1.append(words[wordIndex][letterIndex]);
letterIndex++;
}, 70);
}
typeIt(["beautiful", "awesome", "nice", "wonderful"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myTypingText"></div>
Note that you don't need to .split("")
the word, because you can directly reference the individual characters in a string with the same square-bracket syntax as referencing array elements, e.g., "text"[2]
is "x"
.
You can use setTimeout()
to control the delay in between words:
function typeIt(words) {
var letterIndex = 0;
var wordIndex = 0;
var h1 = $("#myTypingText");
(function nextWord() {
var SI = setInterval(function() {
h1.append(words[wordIndex][letterIndex]);
letterIndex++;
if (letterIndex === words[wordIndex].length) {
wordIndex = (wordIndex + 1) % words.length;
letterIndex = 0;
clearInterval(SI);
setTimeout(function() {
h1.empty();
nextWord();
}, 1000); // delay between words
}
}, 70); // delay between letters
})();
}
typeIt(["beautiful", "awesome", "nice", "wonderful"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myTypingText"></div>
Note that this isn't necessarily the cleanest way to structure the code, but it seemed the quickest way to modify what you already had to achieve the desired output.
Further reading: Immediately Invoked Function Expressions (IIFEs).
Upvotes: 2