title: Reading and setting selector / img width and height
body: <p>I have an <code>img</code> element defined by <code>id</code> in my HTML.  In JavaScript, I have a function that sets that element's image source.  Whatever I tried, I could not get the dimensions back using <code>$('#name').width()</code>.  It would always return zero.</p>
  
  <p>I found a solution on here to get the width and height by creating a new image element and using the <code>onload</code> event to get those values.  I want to set the element's width and height to those values so that I can refer back to them.  No matter what I tried (attr, css, width), I get no results.  I cannot figure it out, so I am hoping someone here can help.</p>
  
  <p><strong>HTML Source</strong></p>
  
  <pre><code>    &lt;div id="image"&gt;
          &lt;img id="photo"&gt;
      &lt;/div&gt;
  
      &lt;div id="debug"&gt;&lt;/div&gt;
  </code></pre>
  
  <p><strong>JavaScript &amp; jQuery Source</strong></p>
  
  <pre><code>$(document).ready(function(){
  ...
      function choosePhoto() {
      $('#photo').attr({
          src: "photo.gif",
          title: "Photo"
      });
  
      // determine width and height of new photo
      var img = document.getElementById('photo'),
          new_img = new Image();
      new_img.onload = function() {
          var imgWidth  = this.width,
              imgHeight = this.height;
  
          // one of my attempts at setting the width
          // value of an element outside this function.
          // 
          // How do I set the width and height values on the element
          // so that I can refer back to them again?
          $('#photo').attr({
              width: imgWidth
          });
  
          // this prints the correct dimensions
          $('#debug')
              .append("Original dimensions are : " + imgWidth + "x" + imgHeight + " pixels");
      }
      new_img.src = img.src;
  
      // this prints zero for the width
      $('#debug')
          .append("Image: " + $('#photo').width() + " x " + $('#photo').height() + "&lt;br /&gt;");
  }
  ...
  });
  </code></pre>