简体   繁体   中英

How to replicate a typing effect using jQuery/JavaScript?

How to have the exact typing effect used on this page? https://www.braintreepayments.com/

<span class="writer" data-writer-command="['PayPal?', 'Apple Pay?', 'Venmo?', 'Bitcoin?']">Ve</span>

Here is the JSFiddle with the extracted library from the website : http://jsfiddle.net/8g6dsp0p/1/

You can initialize the script with this following code :

<span class="writer" data-writer-command="['PayPal?', 'Apple Pay?', 'Venmo?', 'Bitcoin?']"></span>

<script>
$(document).ready(function() {
   new Writer
});
</script>
var word = "Venmo";
var cur = 1;
var intrvl = setInterval(function () {
   $('.writer').html(word.slice(0,cur));
   if(cur >= word.length) {
clearInterval(intrvl);
  }
  else{
   cur++;
  }
}, 500);

JSBin

The above jsBin has the code you require. it is not neatly formatted but code is correct. Again to reproduce the code

<span clas="writer"></span>


    var words = ["Venmo", "alright", "done", "ok"];
var curWord = 0;



function writeWord(word, deleteWord) {
  var cur;
  if(deleteWord){    
    cur = deleteWord.length;
    var delIntrvl = setInterval(function () {

     if(!cur) {
      clearInterval(delIntrvl);
       if(curWord < (words.length - 1)) {
         writeWord(words[++curWord],"");  
       } 
       else {//if you dont need continous looping remove this else statement
         curWord = 0;
         writeWord(words[curWord],"");  
       }      
    }
    else{
      var reqWrd = deleteWord.slice(0,cur);
      console.log(reqWrd);
     $('.writer').html(reqWrd);
     cur--;
    }
    }, 200);
  }
  else {
    cur=1;
    var intrvl = setInterval(function () { 

     if(cur >= word.length) {
      clearInterval(intrvl);       
       writeWord("",word);
    }
    else{
      var reqWrd = word.slice(0,cur);
      console.log(reqWrd);
     $('.writer').html(reqWrd);
     cur++;
    }
    }, 200);


     }


        }

        writeWord(words[curWord], "");

Updating the code and also providing jsBin for continous looping ContinousLoopJsBin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM