JU Home page

Dynamically resizing and changing the image of an HTML <IMG> element

An HTML IMG element defines a rectangular area in your displayed document that is filled with a (possibly rescaled) pixmap. Using HTML events and Javascript it is now easy to switch to another image or resize the current image. For example,
  1. RESIZE IMAGE the picture gets bigger with each click until a quick double-click returns the image to the original size.
            <img
               width="176"
               onclick="this.width*=1.3"
               ondblclick="this.width=176"
               alt="RESIZE IMAGE"
               src="../images/globe_west_2048.jpg"
            />
    
  2. CHANGE IMAGE A click takes you to a new image, a double-click takes you to the original image
            <img
               width="176"
               onclick="this.src='../images/AchillesAjax-Exekias.jpg'"
               ondblclick="this.src='../images/globe_west_2048.jpg'"
               alt="CHANGE IMAGE"
               src="../images/globe_west_2048.jpg"
            />
    
  3. CHANGE IMAGE Clicking on this image cycles thru a list of images. Since the width was set, they will all be resized to the same width as they are being viewed.
            <img
               width="176"
               onclick="
               try{ A=(A % NAMES.length)} catch(e) { A=1 ;NAMES=[
                  '../images/globe_west_2048.jpg',
                  '../images/AchillesAjax-Exekias.jpg',
                  '../images/dutchdoor.gif87',
                  '../images/escher.gif',
                  '../images/semaphore.gif',
                  '../images/semaphore_wave.gif'
               ]};this.src=NAMES[A++];"
               alt="CHANGE IMAGE"
               src="../images/globe_west_2048.jpg"
            />
    
  4. BEST SIZE A click takes you to an optimally sized image (as far as image quality is concerned). A double-click takes you back to the original small image.
            <img
               width="176"
               onclick="this.width=400;this.height=220;"
               ondblclick="this.width=176;this.height=97;"
               alt="BEST SIZE"
               src="../images/AchillesAjax-Exekias.jpg"
            />
    
  5. DOM BEST SIZE You can take this concept as far as you like. Here is an example that uses a JavaScript/ECMAScript switch statement. A click takes you to the default image size; which is usually very clear; even when you do not know the default size. Another click does original_size*4; then another click takes you back to the original size, starting the cycle over (note just the click is used, no double-click is used). This construct can be used to create just about any series of serial actions that is possible with DOM and JavaScript and an image.
            <img
               width="200"
               onclick="
    
               try{ TOGGLEA=(TOGGLEA % 3)}catch(e){
                  TOGGLEA=0;
                  HOLDX=this.getAttribute('width');
                  HOLDY=this.getAttribute('height');
               }; // initialize TOGGLEA, HOLDX, and HOLDY
    
               switch(TOGGLEA){
               case 0: // removing the attribute makes it take on the default size
                       this.removeAttribute('width');
                       //this.removeAttribute('height');
               break;
               case 1: // this makes it four times as big as it was originally
                       this.setAttribute('width' ,HOLDX*4);
                       //this.setAttribute('height',HOLDY*4);
               break;
               case 2: // this sets to a original size
                       this.setAttribute('width' ,HOLDX);
                       //this.setAttribute('height',HOLDY);
               break;
               }
               TOGGLEA++;
               "
               alt="DOM BEST SIZE "
               src="../images/AchillesAjax-Exekias.jpg"
            />
    
  6. ENTER OVER TO RESIZE IMAGE the picture gets bigger when you move the mouse over it; a click returns the image to the original size.
            <img
    	   id="earth1"
               width="176"
               onMouseOver=" 
    	         mye=getElementById('earth1');
    	         zoom=setInterval('mye.width=Math.min(1.02*mye.width,1000)',100);
    	         // delay loop that changes height on hover
    	      "
               onMouseOut="  clearInterval(zoom);
    	   // break the loop setInterval() started when you entered"
               onclick="clearInterval(zoom);this.width=176"
               alt="ENTER OVER TO RESIZE IMAGE"
               src="../images/globe_west_2048.jpg"
            />
    
  7. Example of image popup moving over the picture causes another image to be placed on top by placing an image with absolute coordinates on top of the first image using JavaScript/ECMAScript
    <script language="JavaScript">
    function getElementPosition(obj) {    
       var curleft = curtop = 0;          
       if (obj.offsetParent) {            
          do { curleft  += obj.offsetLeft; curtop   += obj.offsetTop;
          } while (obj = obj.offsetParent); 
       }
       return [curleft,curtop]; 
    }
       function removeAbsoluteOver(objname){ var x = document.getElementById(objname); x.innerHTML=' '; }
    
       function absoluteOver(obj,imgsrc,width,height,lyr){
          var coors = getElementPosition(obj);
          var x = document.getElementById(lyr);
          x.style.position = 'absolute';
          x.innerHTML='<img alt="" src="' + imgsrc + 
             '" width="' + width + '" height="' + height + 
    	 '" onMouseOut="removeAbsoluteOver(\'layer3\');" >';
          x.style.top = coors[1] + 'px'; x.style.left = coors[0] + 'px';
       }
    </script>
       <li> 
       <div id="layer3"></div>
          <img id="earth2" width="176"
            onMouseOver="absoluteOver(this,'../images/globe_west_2048.jpg',500,500,'layer3');"
       	alt="Example of image popup" src="../images/globe_west_2048.jpg"
          />
    
  8. ENTER OVER TO POP UP NEW WINDOW moving over the picture pops another browser window. I would not recommend this in general because popups are often blocked. It seems to behave differently in every browser, anyway (See source for details).
       <img id="earth3" width="176" src="../images/globe_west_2048.jpg" 
             alt="ENTER OVER TO POP UP NEW WINDOW"
          onMouseOver="
             Gstring='width=350,height=350,left=100,top=100'
             Gstring+=',status=no'
             Gstring+=',resizable=yes,scrollbars=no,menubar=no,toolbar=no,location=no,directories=no';
             Gstring+=',copyhistory=no';
             Gstring+=',screenX=350,screenY=350';
          my_window=window.open('../images/globe_west_2048.jpg','bigger earth3',Gstring);"
    
           onclick="
              if(false == my_window.closed){
                 my_window.close ();
    	  }else{
    	     alert('enlarge window already closed!');
    	  }"
       />
    

IMG tips

If you want to get even fancier, make some ECMAScript/JavaScript functions! Tested in iexplore(1), opera(1), safari(1), and firefox(1).

Released: Sat Feb 9, 2008; John S. Urban
VALIDATE HTML5 VALIDATE W3