Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transition element size caused by content changes

I have a button that has some text in it. When you press it, the text changes. This makes the button's width change. It would be great if one could transition the change of an element's width with something like this:

#el {
    transition: width 150ms ease-out;
}

Of course, that only works when you explicitly change the width property.

Does anyone know of an elegant way to achieve this effect? Here's a (yet-to-function) fiddle to hack away at.

like image 481
namuol Avatar asked Oct 31 '12 08:10

namuol


2 Answers

Try this fiddle that does it using jQuery.

$('button').click(function() {
    var width = $(this).css('width');
    var height = $(this).css('height');
    $(this).html('Hello, World!');
    var newWidth = $(this).css('width');
    $(this).css({'width': width, 'height': height});
    $(this).animate({'width': newWidth}, 1000);
});​
like image 89
Maurice Avatar answered Sep 20 '22 07:09

Maurice


With Maurice's answer, the button's text overflowed to a second line, which was worked around by forcing the height of the button to its original height. Instead, use

button {
    white-space: nowrap;
}

so that the button's text stays on one line and is shown while in transition. Then the code no longer has to deal with the button's height, so it can become simpler:

$('button').click(function() {
    var width = $(this).css('width');
    $(this).text('Hello, World!');
    var newWidth = $(this).css('width');
    $(this).css({'width': width});
    $(this).animate({'width': newWidth}, 400);
});

http://jsfiddle.net/2rr54vp2/1/

like image 27
1j01 Avatar answered Sep 20 '22 07:09

1j01