Dynamically change an image with javascript

June 05, 2011 - 06:42

Images displayed in an HTML webpage can be changed with javascript. First use the code below to add an image to your webpage and assign it an ID such as "theimage".

<img src="image1.gif" id="theimage" />


Next at the end of the webpage insert the code which changes the image to the new gif. This code can be added to an onclick event or mouseover to initiate the image change. If the code below is entered as is, then the image will imediatly be changed to image2.gif and the original image wouldn't be seen.

<script language=javascript type="text/javascript">

document.getElementById('theimage').src='image2.gif';

</script>



© 2011 simplevb.net