Some browsers most likely give you an absolute path to the image, rather than the relative path that you provide.
Instead ==, check the location of the indexOf()URL.
Example: http://jsfiddle.net/7Rp2G/2/ (click the button several times to see the URL change)
function changeDivImage() {
var imgPath = new String();
var div = document.getElementById("div1");
imgPath = div.style.backgroundImage;
div.style.backgroundImage = (imgPath.indexOf("blue.png") > -1 || imgPath == "")
? "url(green.png)"
: "url(blue.png)";
}
EDIT: Updated to replace if()with a triple.
source
share