Saturday, July 20, 2013

Javascript to Dynamically Change the Image Source of an Element for IE


Just like the problem of changing background color for IE via Javascript, changing the image source requires special treatment as well.

Here's the solution (simplified for easy reference):

Javascript:

var ie = (navigator.userAgent.indexOf("MSIE") != -1);

if (!ie) {
   document.getElementById('MyImageID').src = 'myImageSrcName.jpg';
}
else {
   document.getElementById('MyElemID').innerHTML = '<img src="myImageSrcName.jpg">';
}


HTML:

<span id="MyElemID">
<img src="original.jpg" id="MyImageID">
</span>


This is a simple example of how to change an image source from original.jpg to myImageSrcName.jpg dynamically across major browsers.

No comments:

Post a Comment