This jQuery function works great letter by letter, but I cannot seem to get it to go word by word.
Any ideas, here is the function:
//Typewriter Effect
$.fn.Typewriter = function(opts){
var $this = this,
defaults = { animDelay: 50 },
settings = $.extend(defaults, opts);
$.each(settings.text, function(i, letter){
setTimeout(function(){
$this.html($this.html() + (letter!='\n'?letter:'<br />'));
}, settings.animDelay * i);
});
}
Thanks!
Don't use $.each
to iterate over a string, and use .text
for setting text instead of .html
.
To change your effect from single chars to whole words, just split the input text into words:
$.fn.Typewriter = function(opts){
var $this = this,
defaults = { animDelay: 50 },
settings = $.extend(defaults, opts),
words = settings.text.split(/(?=\s)/), // split before every whitespace
i = 0;
function animate() {
if (i==words.length) return;
$this.text(words.slice(0, i++).join(''));
setTimeout(animate, settings.animDelay);
}
animate();
}
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.