1

I'm using a small function I found in another thread that works out the width of the text in a div, this works great. I can also animate to the given width, but when I try to animate the width after I have animated the font size, I have issues.

I've figured out it's animating the new width to the width before the font-size is adjusted but can't figure out how to get to work all in one smooth callback.

Please see the basic below fiddle, in which you can run increaseFont and then increaseWidth separately and get the right result. But run bothTogether and it doesn't work. Please press reset between each test.

http://jsfiddle.net/b9uQp/

Community
  • 1
  • 1
dev
  • 3,969
  • 3
  • 24
  • 36

2 Answers2

3

As everything is happening asynchronously, the $('.text').textWidth() is not returning the actual size during the animation execution. Try the 'complete' option and work something out with a callback function: http://docs.jquery.com/Effects/animate#toptions

Tom Walters
  • 15,366
  • 7
  • 57
  • 74
the_marcelo_r
  • 1,847
  • 22
  • 35
2

pretty much what i did was added a parameter to your function to take in a font size. and calculate the width of that.

$.fn.textWidth = function(fontSize){
  var html_org = $(this).html();
    var html_calc = '<span style="font-size:'+fontSize+'">' + html_org + '</span>';
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};

here you will see your jsfiddle updated:

http://jsfiddle.net/Morlock0821/b9uQp/5/

Pedro Estrada
  • 2,384
  • 2
  • 16
  • 24
  • Thanks alot that works great. Unfortunately I've got another issue now, I also want to start the block off smaller and when clicked for it to increase with the font size. Please see this http://jsfiddle.net/b9uQp/7/ . I have a little work around to just add an invisible connector between the words so it thinks it is one word but would you have an idea how I could fix this in the animation? FIDDLE OF WORKAROUND -> http://jsfiddle.net/b9uQp/8/ – dev Dec 15 '12 at 13:46
  • 1
    Hey, no problem! Yeah i would just add the `white-space:nowrap` css to `.text`. here it is in [jsfiddle](http://jsfiddle.net/Morlock0821/b9uQp/9/) – Pedro Estrada Dec 17 '12 at 15:37
  • Of course! I didn't think of that.. thanks again, a nice easy fix. – dev Dec 17 '12 at 16:29