Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Will Rickards http://willrickards.net/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

javascript image swap using DOM

Here is a javascript image swap that uses the DOM methods.
It uses them to support swapping images with different sizes.
Just changing the src property causes the swapped images to be distorted in IE.
This script uses replaceChild instead.

var blnDOMSUPPORT = (document.getElementById) ? true : false;
window.onload = window_load;

function window_load()
   {

   if ( blnDOMSUPPORT )
      {

      document.getElementById('icon1').onclick = swapimage;
      document.getElementById('icon2').onclick = swapimage;
      document.getElementById('icon3').onclick = swapimage;
      
      }
   else
      {

      document.images['icon1'].onclick = swapimage;
      document.images['icon2'].onclick = swapimage;
      document.images['icon3'].onclick = swapimage;

      }

   }

function swapimage()
   {
   
   if ( blnDOMSUPPORT )
      {

      var imgMain = document.getElementById('mainimage');
      var divParent;

      // create new image element
      var imgNew = document.createElement('img');

      // give it an image
      // here I use the src of the icon just for convenience
      // you'd want to somehow determine the src of your desired image
      imgNew.src = this.src;
   
      // give it an id
      imgNew.id = 'mainimage';

      // replace image
      divParent = imgMain.parentNode;
      divParent.replaceChild(imgNew, imgMain);

      }
   else
      {

      // old school image swap
      document.images['mainimage'].src = this.src;

      alert( 'old school' );

      }
   
   }         


It would be used with HTML like this
<div id="main">
<img id="mainimage" src="http://www.w3schools.com/css/smiley.gif">
</div>
<div id="icons">
<img id="icon1" src="http://www.w3schools.com/css/smiley.gif">
<img id="icon2" src="http://www.w3schools.com/images/vxhtml.gif">
<img id="icon3" src="http://www.w3schools.com/images/print.gif">
<input type="button" value="Toggle DOM Support" onclick="window.blnDOMSUPPORT = !window.blnDOMSUPPORT;">
</div> 
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS