Underline animation

by paska

HTML

<p id="text">
    Some initial text
</p>
<button id="btn">Change text</button>

CSS

p {
    text-decoration: underline;
}

JavaScript

$(function() {
	var $text = $("#text"),
    	i = 0,
        timer,
        tick = 100; // ms
	$("#btn").on("click", function() {
    	var $this = $(this);
        $this.prop("disabled", true);
    	animateTextChange(i % 2 == 0 ? "Some text" : "Some other text", function() {
        	$this.prop("disabled", false);
        });
        i++;
    });
    function animateTextChange(newText, success) {
    	var $span1 = $("<span></span>").css("text-decoration", "underline"),
        	$span2 = $("<span></span>").html(newText);
    	$text.css("text-decoration", "none")
        	.empty()
            .append($span1)
            .append($span2);
        timer = setInterval(function() {
        	var pendingText = $span2.text();
            if (!pendingText) {
            	// It's all done!
                clearInterval(timer);
                timer = null;
                $text.css("text-decoration", "underline").html($span1.text());
                if ($.isFunction(success))
                	success.call();
            }
            else {
            	// Move letter by letter from span2 to span1
                $span1.append(pendingText.substr(0, 1));
                $span2.text(pendingText.substr(1));
            }
        }, tick);
    }
});