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.
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);
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With