jQuery if/else statement CSS

10,728

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
Share:
10,728
nmsdvid
Author by

nmsdvid

Updated on June 14, 2022

Comments

  • nmsdvid
    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
    steveax about 12 years
    Yup, the background-image url gets a fully qualified path. Fiddle: jsfiddle.net/TKUET
  • steveax
    steveax about 12 years
    Quoting the path is optional and both single and double quotes are fine.
  • Steve
    Steve about 12 years
    Sure, 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
    steveax about 12 years
    In 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)