Tafadzwa Gonera
Tafadzwa Gonera

Reputation: 352

Image swap won't work in Firefox but works in Chrome and IE

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>    

Upvotes: 1

Views: 277

Answers (4)

Bill
Bill

Reputation: 33

$('button#swap').toggle(function() {
$("div#first > img").attr('src','22b.jpg');
$("div#second > img").attr('src','22a.jpg');
}, function() {
$("div#first > img").attr('src','22a.jpg');
$("div#second > img").attr('src','22b.jpg');
});

Would something like this work for you?

Upvotes: 0

dragon66
dragon66

Reputation: 2715

You only have two images in your HTML so imgArray[2] is not defined. Use a temp var to swap the other images.

Upvotes: 1

mgiuffrida
mgiuffrida

Reputation: 3569

document.images is readonly in Firefox (link to specification). You can create a new image, but you can't append it to the document.images array.

A better way to accomplish image swapping would look something like this:

document.getElementById("swap").onclick = function(){
    if(document.images){
        var imgArray = document.images;
        var tempSrc = imgArray[0].src;
        imgArray[0].src = imgArray[1].src;
        imgArray[1].src = tempSrc;
    }
};

Upvotes: 4

Marcus Johansson
Marcus Johansson

Reputation: 2667

Have you tried putting it in some sort of ready-function?

Upvotes: 0

Related Questions