jQuery if/else statement CSS
Solution 1
It appears that the right answer is to write the full path to the image. So, use url(http://www.myhost.com/img/image.png)
instead of url(img/image.png)
.
Solution 2
There could be a subtle difference in the value; alert the value in the else statement to see what's going on. For example,
if ( $("#div2").css("background-image") === "url(img/image.png)") {
alert('OK');
}
else {
alert($("#div2").css("background-image"));
}
Solution 3
My guess would be that when the css loads, it is taking url(img/image.png) and turing that into http://www.somehost.com/img/image.png. Thus, .css("background-image") would no longer equal "url(img/image.png)".
Instead of checking
.css('background-image') == 'url(img/Image.png)'
check
.css('background-image').indexOf("img/Image.png") != -1
nmsdvid
Updated on June 14, 2022Comments
-
nmsdvid almost 2 years
I have an interesting problem that I don't understand. It's a simple jQuery if else statement, but it's not working. Why is it not working?
Code:
$("#div").click(function(){ if ( $("#div2").css("background-image") === "url(img/image.png)") { alert('OK'); } else { alert('NG'); } });
But when I change
.css("background-image") === "url(img/image.png)"
, for example, to.css('position') === 'absolute'
, it's working. -
steveax about 12 yearsYup, the
background-image
url gets a fully qualified path. Fiddle: jsfiddle.net/TKUET -
steveax about 12 yearsQuoting the path is optional and both single and double quotes are fine.
-
Steve about 12 yearsSure, both are fine when declaring the path in the stylesheet. The question here, however, is: What does $("#div2").css("background-image") return? A string with or without the single quotes. This might be a browser dependent answer, so doing an indexOf, as Daniel suggests above, might be the safest way to go.
-
steveax about 12 yearsIn Firefox at least, the full path is returned and enclosed in double quotes:
url("http://thesite.tld/path/to/image.png")
(see my fiddle above)