title: HTML + Javascript: Dynamic Image Resize?
body: <p>I am trying to get some <code>JavaScript</code> to programmatically adjust a HTML <code>img</code> tag's width to display various sized images correctly.</p>
  
  <p>I have a fixed width <code>img</code> tag at <code>800px</code> to display an image, this is the max width.</p>
  
  <p>If the image is wider then <code>800px</code> I want to display it at <code>800px</code> wide;</p>
  
  <p>If the image is less than <code>800px</code> wide I want to preserve its width to avoid stretching it.</p>
  
  <p>I use this html/javacript code to get a partial solution:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function resize_image(id) {
   var img = document.getElementById(id);
   var normal_width = img.width;
   img.removeAttribute("width");
   var real_width = img.width;
   if (real_width &lt; normal_width) {
    img.width = real_width;
   } else {
    img.width = normal_width;
   }
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;img id="myimage" onload="resize_image(self.id);" src="https://via.placeholder.com/350x150" width="800" /&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>The above code seems to work on all browsers I have tested except <code>Safari</code> (images don't display unless you refresh the page).</p>
  
  <p>I know I can use CSS <code>max-width</code> but that wont work on <code>IE</code> &lt; 7 which is a show stopper.</p>
  
  <p>How can I get this working for all browsers? Many thanks in advance.</p>