PDA

View Full Version : Javascript swaping images


beautyfiend
07-01-2009, 01:50 PM
Hi, I am trying to swap 2 images over when a button is pressed but something is wrong with my code.
Any help much appreciated!

<html>
<head>
<script type="text/javascript">
function swap_images() {
images=document.getElementsByTagName("img");
images0=images [0].attributes[0].nodeValue;
images1=images [1].attributes[0].nodeValue;
images [1].attributes[0].nodeValue=images0;
images [0].attributes[0].nodeValue=images1;
}
</script>
</head>
<body>
<form id="myform">
<input type="button" value="Switch" onclick="swap_images()" />
</form>
<br /><br />
<img src="HMT STUFF/HMT/images/elvis.jpg" width="219" height="236" alt="Elvis"/>&nbsp;&nbsp;&nbsp;
<img src="HMT STUFF/HMT/images/mj.jpg" width="231" height="236" alt="MJ"/>
</body>
</html>

yell0wdart
07-01-2009, 04:17 PM
You've got a few problems. First, make sure to initialize your variables with the keyword "var". Secondly, you're probably not capturing the src attribute of your <img> through nodeValue.

You probably want something closer to this:


<script type="text/javascript">

function swap_images()
{
var images = document.getElementsByTagName("img");
var images0 = images[0].src;
var images1 = images[1].src;
images[1].src = images0;
images[0].src = images1;
}

</script>



Also, if you're developing JS quite a bit, you might want to use FireFox. I'd recommend using the FireBug and WebDeveloper Toolbar addons. The Error Console is also very useful (in the Tools menu).

beautyfiend
07-01-2009, 05:58 PM
Thank you very much yell0wdart! It works!
I am new to this JS game. I will check out those firefox add-ons. Thanks again.;)