Dan
Dan

Reputation: 12096

jQuery animate width on button text change

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

http://jsfiddle.net/HYZbA/41/

Upvotes: 2

Views: 2702

Answers (4)

Piotr Uchman
Piotr Uchman

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

j08691
j08691

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);
})

jsFiddle example

Upvotes: 2

David Hewitt
David Hewitt

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

Tomzan
Tomzan

Reputation: 2818

You cannot animate width/height to auto,

instead you give an invisible similar element width/height auto and saves their calculated value, then animate your own element with the calculated value.

Here is a link that explain how to do it.

Upvotes: 1

Related Questions