Subtitles

by soulwire

HTML

<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>
<header>
    <h1>
        <span>Example text</span>
    </h1>
</header>

CSS

html, body {
    -webkit-backface-visibility: hidden;
    font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
    padding: 20px;
}
header {
    overflow: hidden;
    height: 68px;
    width: 100%;
}
span {
    text-transform: uppercase;
    background: #111;
    padding: 8px;
    display: inline-block;
    color: #fff;
}

JavaScript

var tf = $('h1');
var phrases = [
    'Lorem ipsum dolor',
    'consectetur adipiscing elit',
    'Maecenas a cursus',
    'Suspendisse mauris arcu, iaculis',
    'Maecenas tincidunt convallis purus sed facilisis'
];
var count = 0;

function type( text ) {
    
    var a = tf;
    var b = tf.clone();
    var t = b.find( 'span' );
    
    // Type
    var p = {n:0};
    $(p).animate({
        n:1
    },{
        duration: 300,
        easing: 'easeOutQuad',
        step: function( now ) {
            var i = Math.floor( now * text.length );
            t.text( text.substr( 0, i ) + ( i < text.length ? '_' : '' ) );
        }
    });
    
    // Shift
    a.after(b);
    a.stop().delay(100).animate({
        marginTop: -a.outerHeight()
    },{
        duration: 250,
        easing: 'easeInOutQuad',
        complete: function() {
            a.remove();
        }
    });
    
    tf = b;
}

$( document ).click(function() {
    type( phrases[ ++count % phrases.length ] );
});