SPGuar SPGuar - 6 months ago 64
Javascript Question

Running text effect

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");


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.


You can modify your existing function to accept an array of words, and process the words one by one:

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
  }, 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".