Friday, March 18, 2016

Display word one by one

To display word one by one.

Shorter delay, and a longer animation, so the animations overlap a little:

var str = "Happy New Year 2011";

var spans = '<span>' + str.split(/\s+/).join(' </span><span>') + '</span>';

$(spans).hide().appendTo('body').each(function(i) {
    $(this).delay(400 * i).fadeIn(1000);
});

Another example:

var str = "Happy New Year 2011";

var spans = '<span>' + str.split(/\s+/).join(' </span><span>') + '</span>';

$(spans).hide().appendTo('body').each(function(i) {
    $(this).delay(1000 * i).fadeIn();
});

Another example that deals with tag:

<style>
strong {
    font-weight: bold;
}
</style>

<div id="greeting">
    <h1>here is a test text. <strong>We believe this is better</strong> than ever.</h1>
</div>

<script>
$(document).ready(function() {
    var h1 = $('div#greeting h1');

    h1.hide().contents().each(function() {
        var words;
        if (this.nodeType === 3) {
            words = '<span> ' + this.data.split(/\s+/).join(' </span><span> ') + ' </span>';
            $(this).replaceWith(words);
        } else if (this.nodeType === 1) {
            this.innerHTML = '<span> ' + this.innerHTML.split(/\s+/).join(' </span><span> ') + ' </span>';
        }
    });

    h1.find('span').hide().each(function() {
        if (!$.trim(this.innerHTML)) {
            $(this).remove();
        }
    });

    h1.show().find('span').each(function(i) {
        $(this).delay(400 * i).fadeIn(600);
    });
});
</script>

Reference:

http://stackoverflow.com/questions/4607613/jquery-text-effect-where-words-appear-one-by-one

No comments: