Melodin
Melodin

Reputation: 15

Javascript only works once?

I don't know why, but my Javascript only works once in Firefox and IE (but it works fine in Chrome). Does anybody know why?

<script type="text/javascript">
function changeDivImage() 
       { 
        var imgPath = new String(); 
        imgPath = document.getElementById("div1").style.backgroundImage; 
        if (imgPath == "url(images/1.jpg)" || imgPath == "")
          { 
           document.getElementById("div1").style.backgroundImage ="url(images/2.jpg)"; 
          } 
        else if (imgPath == "url(images/2.jpg)")
          { 
           document.getElementById("div1").style.backgroundImage = "url(images/3.jpg)"; 
          }
        else if (imgPath == "url(images/3.jpg)")
          { 
           document.getElementById("div1").style.backgroundImage = "url(images/1.jpg)"; 
          }  
       }   
  </script> 

Script is triggered by clicking on image

<img src="images/leftarrow.png"
     value="Change Background Image"
     onclick="changeDivImage()" />

Upvotes: 1

Views: 408

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Browsers tend to normalise CSS properties in different ways. IE and Firefox put quotes around the URL, for instance.

So, perhaps you should try this instead:

var div = document.getElementById('div1'),
    imgPath = parseInt(div.style.backgroundImage.match(/\d(?=\.jpg)/) || ["0"],10),
    newnum = imgPath%3+1;
div.style.backgroundImage = "url(images/"+newnum+".jpg)";

Upvotes: 1

Related Questions