Reputation: 9996
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.
Upvotes: 6
Views: 3149
Reputation: 4180
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/
Upvotes: 1
Reputation: 56
I guess this' impossible, because the browser can't get the exact target width; Let's suppose it got the value before transition, but at that time ,the button has arrived the width! Maybe the tansition exists, and we can't see it. so you need an initial width, and you need to know the target width too, us js
Upvotes: 0
Reputation: 27632
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);
});
Upvotes: 2