Take the 2-minute tour ×

I'm running into an issue with an image swap script I'm working on. It works beautifully in Chrome and IE 8 but in Firefox I'm getting IMG1 Not Defined. I've tried using var image1 = document.getElementById("IMG1") but then I just get image1 is NULL. Any help on this would be appreciated. Here's my code and markup.

<script type="text/javascript">

    function imgSwap() {
        IMG1.src = "/images/stories/clubpics_on.png";
        IMG2.src = "/images/stories/facebook_off.png";
function imgSwap2() {
        IMG1.src = "/images/stories/clubpics_off.png";
        IMG2.src = "/images/stories/facebook_on.png";

  <img src="/images/stories/clubpics_on.png" name="IMG1" id="IMG1" class="IMG1" style="position:absolute; left:-19px; width:165px" value="IMG1" onclick="imgSwap();"/ >

<img src="/images/stories/facebook_off.png" class="IMG2" value="IMG2" name="IMG2" id="IMG2" style="position:relative; left:123px; width:165px"  onclick="imgSwap2();" />
share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

Firefox does not automatically create global references to elements that have "id" values. Use document.getElementById("IMG1") instead.

If you tried that assignment statement for the variable "image1" outside the two functions, the variable would be null because that code would run before the element were added to the DOM. If you put that code inside the functions, it will work.

share|improve this answer
+1 i tried it and it works, i wonder why he says it doesnt –  Ibu Nov 23 '11 at 18:34
@Ibu probably he had the assignment outside the functions, which would run before the elements became part of the DOM. –  Pointy Nov 23 '11 at 18:35
@Ibu on first pass/click it may dosn't work well on FF3 that is, not until you for example click the second time it gets reference to it. –  david Nov 23 '11 at 18:45
Thank you, you're a life saver –  jdpipikin Nov 23 '11 at 18:45
add comment

Your Answer


