May 11
25
Easy Javascript Image Swapping Function
Sometimes you just need a quick image swapping script so here is one you can use quickly. You could always do this right inline too but why? I want to use the same script over and over and want to be able to place the images anywhere so this is how I do this.
- Create your HTML image statement and give it an ID tag.
<img src="images/image1.gif" ID="TestID"/>
- Now add a script section and create a name for your new function. ImageID will be the images ID tag and ImageFileName will be the file name and path that will be passed to the function.
<script type="text/javascript">
function changeImage(ImageID,ImageFileName)
{
}
</script>
- Now we need to add the function which is very easy, it's one line long and the script will look like this.
<script type="text/javascript">
function changeImage(ImageID,ImageFileName)
{
document.getElementById(ImageID).src = ImageFileName;
}
</script>
- Now we just need to add the calls in the image tag. It will look something like this.
<img src="images/image1.gif" id= "TestID"
onmouseover="changeImage('TestID','images/image2.gif')"
onmouseout="changeImage('TestID','images/image1.gif')" />
That's it. It's a pretty basic function but now you can re-use this all the time for image swapping.