Reputation: 12096
If I have a button like this with default css, how can I make it so when you click the button, the text changes and it's width is animated to fit in the new text?
HTML
<button>Click Me</button>
jQuery
$(document).on("click", "button", function(){
$(this).text("You have clicked me!", function(){
$(this).animate({width:"auto"}, 1000);
});
})
jsFiddle
Upvotes: 2
Views: 2702
Reputation: 570
You can try:
$("button").click(function(){
var widthOld = $(this).width();
$(this).text("You have clicked me!");
var widthNew = $(this).width();
$(this).animate({width: widthOld+'px'},0).animate({width:widthNew+"px"}, 1000,
function() {$(this).css('width', 'auto');}
);
});
Upvotes: 1
Reputation: 207901
$("button").click(function () {
var oldWidth = $(this).width();
$(this).text("stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff");
var newWidth = $(this).outerWidth();
$(this).width(oldWidth);
$("button").animate({
width: newWidth + 'px'
}, 1000);
})
Upvotes: 2
Reputation: 837
Here is an example that sort of works, you'll need to play with it a little http://jsfiddle.net/HYZbA/47/
But as said by Tomzan, it isn't possible to animate width to auto, so that example uses the workaround.
I fix the width first, and then change the text and animate, this prevents the button doing auto width by itself.
$("button").bind("click", function(e){
$(this).css("width", $(this).width());
$(this).text("test test test test test test test");
$(this).animateAuto("width", 1000);
Upvotes: 2