0

Looking for a way to slowly render text letter-by-letter (for a lack of a better description), I came across this solution. While this works fine for plain text, my problem is that I would like to append html-strings, i.e. text that has already been formatted with html-tags (<h1>, <p>, etc.). Since using jQuery's apend() fundction prints each letter on its own line, the resulting text cannot be parsed as html anymore and all I get inside my div is raw text (with visible html tags).

Now, is there any other way to do this while avoiding new lines?

I already tried using a jQuery animation on the width of a div pre-filled with my text (see here), but that doesn't look the way I want it to - when showing multi-line text it shows all lines at once, while I would like ti to be rendered letter by letter.

As always, thank you in advance and I'm looking forward to your suggestions!

My code so far:

function renderUI(levelId) {    
    [ unrelated code ]

    var showText = function (target, message, index, interval) {    
      if (index < message.length) { 
        $(target).append(message[index++]); 
        setTimeout(function () { showText(target, message, index, interval); }, interval); 
      } 
    };

    setTimeout(function() {
        $( "#introOverlay" ).slideDown(1000, function() {
            var target = $($("iframe").contents()).find("#ioMainLeft");
            var msg = target.html();
            target.html("");
            console.log(msg);
            showText(target, msg, 0, 16);
        });
    }, 3500);

    [ unrelated code ]
}

1 Answer 1

1

Where you looking for something like this http://jsfiddle.net/4hqCJ/5/ ?

var typeHiddenMsg = function (targetId, html, index, interval){
    if ( index == html.length ) return;

    $(targetId).html( html.substr(0,index) );

    setTimeout(function () {
        typeHiddenMsg(targetId, html, ++index, interval); 
    }, interval);
}

$(function () { 
  typeHiddenMsg("#target",$("#hidden_message").html(), 0, 100);    
}); 
Sign up to request clarification or add additional context in comments.

2 Comments

I was looking for this exactly! So you use $.html() to replace the whole html with itself plus one letter each time. Wouldn't have thought of that in ages :D. Only small concern I'd have is that it might have an increasing impact on performance the longer the text gets...although that might just be my overly cautious mind. Anyway, I'll give this a try asap - thank you very much for your help ! Much appreciated.
No problem, It's def not the most efficient way but more along the line of what you had

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.