d-_-b
d-_-b

Reputation: 23211

Jquery - Animate innerHTML possible?

I'm trying to have a function that does setTimeout, then changes the innerHTML:

<script type="text/javascript">
    $(document).ready(function(){
        setTimeout(function(){
            document.getElementById("middlecolor").innerHTML='new text new text';
        }, 1000);
    });
</script>

Question: How could I animate the new text that appears, i.e. line by line as opposed to being written all at once?

Thanks for any suggestions!!

Upvotes: 2

Views: 6088

Answers (3)

Bergi
Bergi

Reputation: 665546

Line-by-line is a bit tricky, but possible.

var ps = document.getElementById("text").children;
var i = 0;
var $p = $(ps[i]);

setTimeout(function newline(){
$p.css("height", function(index, h){
    h = parseInt(h);
    h += parseInt($p.css("line-height"));
    console.log(h,  ps[i].scrollHeight);
    if (h > ps[i].scrollHeight)
        $p = $(ps[++i]);
    return h;
}); 
if (i < ps.length)
    setTimeout(newline, 200);
}, 200);​

I'd suggest to use a typewriter effect, which is also very likable: http://jsfiddle.net/pZb8W/1/

var ps = document.getElementById("text").children;
var i = 0;
var $p, text;
var speed = 20;

setTimeout(function newchar(){
if (!text) {
    $p = $(ps[i++]); 
    text = $p.text();
    $p.empty().show();
}
$p.append(document.createTextNode(text.charAt(0)));
text = text.slice(1);
if (text.length || i < ps.length)
    setTimeout(newchar, Math.random()*speed+speed);
}, 3*speed);​

Upvotes: 3

Jorge Olivares
Jorge Olivares

Reputation: 1492

Try something like this:

<div id="text">
</div>

$(document).ready(function () {
    var interval = setInterval(function () {
        $('#text').append('<p style="display: none;">new text</p>');
        $('#text p:last').fadeIn('slow');
    }, 5000);
});

See the example here

If you want to kill the interval, can be doing this:

clearInterval(interval);

Greatings.

Upvotes: 4

jfriend00
jfriend00

Reputation: 708146

Here's a function that would animate in multiple lines of text, one after the other:

<script type="text/javascript">
$(document).ready(function(){

function animateAddText(id, text, delta) {
    var lines = text.split("\n");
    var lineCntr = 0;
    var target = $("#" + id);

    function addLine() {
        if (lineCntr < lines.length) {
            var nextLine = "";
            if (lineCntr != 0) {
                nextLine = "<br>";
            }
            nextLine += lines[lineCntr++];
            $("<span>" + nextLine + "</span>").hide().appendTo(target).fadeIn(1000);
            setTimeout(addLine, delta);
        }
    }
    addLine();
}

var multilineText = "First line\nSecond Line\nThird Line\nFourth Line\nFifth Line";
animateAddText("middlecolor", multilineText, 1000);

});
</script>

And a working demo: http://jsfiddle.net/jfriend00/Gcg5T/

Upvotes: 1

Related Questions