Autoresize div to fit inner image

Autoresize div to fit inner image

Hello,

I write a plugin to resize the outer div to fit the image (so that the caption wraps properly). The markup is something like this:
  1. <div class="image-container image-center">
  2.   <a href="url/to/orig"><img src="url/to/scaled" alt="Caption"/></a>
  3.   <div>Caption</div>
  4. </div>
My jQuery code is:
  1. // Auto resize div container of image
  2. (function($){
  3.   $.fn.autoresize = function() {
  4.     if (this.width() > 0) {
  5.       this.parent().parent().width(this.width());
  6.     }
  7.     else {
  8.       setTimeout(this.autoresize(), 500));
  9.     }
  10.   };
  11. })(jQuery);
  12. Drupal.behaviors.autoResize = function (context) {
  13.   $('.image-container img').autoresize();
  14. };
But it sometimes it doesn't work as expected: the div width can be 0 or 28px (I don't know from where this comes). The Drupal.behaviors is called after the dom ready.
I'm a newcomer to jQuery. Please help.