Rick Joe Rick Joe - 1 year ago 76
Javascript Question

missing part of string - not writing the last letter

I want a type effect in jquery.

the problem is, it is not writing the last letter of the string.

'How are you?' will leave the

?


var str = 'how are you?', i = 0, isTag, text;
(function type() {
text = str.slice(0, ++i);
if (text === str) return;
document.getElementById('m').innerHTML = text;
var char = text.slice(-1);
if( char === '<' ) isTag = true;
if( char === '>' ) isTag = false;
if (isTag) return type();
setTimeout(type, 100);
}());


https://jsfiddle.net/9a8Lbgwc/

Answer Source

You should swap the following lines:

if (text === str) return;
document.getElementById('m').innerHTML = text;

In the last iteration you are existing the function before updating the html content.