I’m trying to swap two images in two divs on click event, so that 22a.jpg ends up in div#second and 22b.jpg ends up in div#first, but every time I click the “swap” button I get this error in Firebug: imgArray[2].src is undefined. I tried to run the code in Chrome 17.0.963.2 and IE 8.0, and it works just fine with no errors. I’m using Firefox 11.0
HTML
<body>
<div id = "first" class = "thumbnail">
<img class = "thumbsize" src = "22a.jpg" />
</div>
<div id = "second" class = "thumbnail">
<img class = "thumbsize" src = "22b.jpg" />
</div>
<input type = "button" id = "swap" value = "swap" />
</body>
JS
<script type = "text/javascript">
document.getElementById("swap").onclick = function(){
if(document.images){
var imgArray = document.images;
imgArray[2] = new Image();
imgArray[2].src = imgArray[0].src;
imgArray[0].src = imgArray[1].src;
imgArray[1].src = imgArray[2].src;
}
};
</script>
document.imagesis readonly in Firefox (link to specification). You can create a new image, but you can’t append it to thedocument.imagesarray.A better way to accomplish image swapping would look something like this: