title: How to add callback to a function
body: <p>I have the following function:</p>
  
  <pre><code>/* **************************** */
  // GET REAL DIMENSIONS OF ELEMENT
  /* **************************** */
  $.fn.getRealDimensions = function (outer) {
      var $this = $(this);
      if ($this.length == 0) {
          return false;
      }
      var $clone = $this.clone()
          .show()
          .css('visibility','hidden')
          .appendTo('body');        
      var result = {
          width:      (outer) ? $clone.outerWidth() : $clone.innerWidth(), 
          height:     (outer) ? $clone.outerHeight() : $clone.innerHeight(), 
          offsetTop:  $clone.offset().top, 
          offsetLeft: $clone.offset().left
      };
      $clone.remove();
  
      return result;
  }
  </code></pre>
  
  <p>This function returns dimensions of an element on my page. However, my call to this runs faster than the function can operate and 'dimensions' isn't set correctly. My call is:</p>
  
  <pre><code>dimensions = $('#backgroundCroppingDiv').getRealDimensions();
  myWidth = dimensions.width; // myWidth INCORRECT BECAUSE FNC HASN'T FINISHED
  </code></pre>
  
  <p>I want to implement a 'callback' function so that myWidth doesn't get set until the 'getRealDimensions' function has finished and calculated the dimensions.</p>
  
  <p>I tried the following:</p>
  
  <pre><code>/* **************************** */
  // GET REAL DIMENSIONS OF ELEMENT
  /* **************************** */
  $.fn.getRealDimensions = function (outer, callback) {
      var $this = $(this);
      if ($this.length == 0) {
          return false;
      }
      var $clone = $this.clone()
          .show()
          .css('visibility','hidden')
          .appendTo('body');        
      var result = {
          width:      (outer) ? $clone.outerWidth() : $clone.innerWidth(), 
          height:     (outer) ? $clone.outerHeight() : $clone.innerHeight(), 
          offsetTop:  $clone.offset().top, 
          offsetLeft: $clone.offset().left
      };
      $clone.remove();
  
      if (typeof(callback) == 'function') {
      callback(result);
      }
      //return result;
  }
  </code></pre>
  
  <p>And then calling it with this:</p>
  
  <pre><code>dimensions = $('#backgroundCroppingDiv').getRealDimensions( function() {
      myWidth = dimensions.width;
  });
  </code></pre>
  
  <p>But to no avail...</p>
  
  <p>Does anyone know how to achieve the functionality that I need? </p>
  
  <p>Thanks :-)</p>