mango mango - 4 months ago 35
CSS Question

Is there a way to animate the transition from text-align left to center in an input box

Fiddle: http://jsfiddle.net/p7gFh/

html:

<input id = 'box' value = 'some text'/>


css:

#box {
text-align:left;
}


js:

$('#box').on('click', function() {
$(this).css({'textAlign':'center'}, 500);
});


Right now the text just snaps to the center on click. I tried .animate() but nothing happened. Is there a way to animate a smooth transition from text-align left to center without snapping?

Answer

The only real way to achieve this is through some funky behind-the-scenes magic, using a temporary element that mimics the text inside the input.

Here's a working example: http://jsfiddle.net/xLg93/

$('#box').on('focus', function () {
    var full_width = $(this).width();
    var t = document.createElement('span');
    t.innerHTML = $(this).val();
    t.style.visibility = 'hidden';
    document.body.appendChild(t);
    var text_width = $(t).width();
    document.body.removeChild(t);
    $(this).animate({
        'text-indent': (full_width - text_width) / 2
    });
});

Keep in mind you'll have to style the temporary element's font-size, font-face and letter-spacing to be identical to the input box, otherwise it won't animate to the exact center.

Comments