[thelist] image swap works in Firefox and IE, not Chrome or Safari

Ms2ger ms2ger at gmail.com
Tue Feb 15 15:26:49 CST 2011


On 2011-02-15 09:53 PM, Joel D Canfield wrote:
> Testing on Win7 right now. This works in Firefox and IE, does nothing at all
> in Chrome and Safari. The code validates in HTML Tidy but I'm always
> suspicious of my javascript.
>
> What's broken here?
>
> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "
> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
> <html>
> <head>
> <title>Image Swap Javascript Example</title>
> <script type="text/javascript">
> image1 = new Image()
> image1.src = "papago_park_oasis.jpg"
> image2 = new Image()
> image2.src = "joel.jpg"
> image3 = new Image()
> image3.src = "tree_in_rock_2.jpg"
> </script>
> </head>
> <body>
> <div style="width:128px;float:right;border:1px solid
> #122559;padding:1em;margin:1em;">
> <a href="#" onclick="imageSwap.src='papago_park_oasis.jpg';">Oasis</a><br />
> <a href="#" onclick="imageSwap.src='joel.jpg';">Joel</a><br />
> <a href="#" onclick="imageSwap.src='tree_in_rock_2.jpg';">Tree</a>
> </div>
> <div style="float:left;width:512px;border:1px solid
> #122559;padding:1em;margin:1em;">
> <img src="joel.jpg" id="imageSwap" />
> </div>
> </body>
> </html>

I note first that this code doesn't work in Firefox, but I think it 
would in Safari/Chrome.

Your problem lies in

     onclick="imageSwap.src='papago_park_oasis.jpg';"

Using an element's id as a variable in this way is not very well 
supported, and not really good practice either. A better solution would be:

     <script>
     function swap(src) {
       document.getElementById('imageSwap').src = src;
       return false;
     }
     </script>
     ...
     <a href="#" onclick="swap('papago_park_oasis.jpg');">Oasis</a><br />
     <a href="#" onclick="swap('joel.jpg');">Joel</a><br />
     <a href="#" onclick="swap('tree_in_rock_2.jpg');">Tree</a>

Note the |return false;|, which prevents the browser from loading the 
URL in the href attribute.

HTH
Ms2ger


More information about the thelist mailing list