I’m currently trying jQuery and I would like to know how can you check the background color of an element.
What I have is a button and a div that when the button is clicked the div changes to a different color but what I want is to change the background color only if the current color is blue, but if the current color is not blue leave it as is? Something like, if background color is blue , change it to red.
In the example below it changes the color to red even though I’m checking for blue, in reality this should leave the color as green since the if statement is false. I know I’m doing it wrong thats why is not doing what I’m trying to accomplish.
Again I’m just practicing and the question is how to determine the current background color of an element and change it based on that using an IF statement.
I think you have the .css() method confused as far as how it actually works, when you call the method and supply it 2 arguments it sets the value (the second argument) based on the property (the first argument). What you need to do instead of simply call .css() but just supply the property name aka background-color which will return the property value instead of setting it, see the below example.
if (firstDiv.css('background-color') === 'blue') {
I haven’t looked at the source but from what I know about jQuery I don’t think the css() method looks at computed styles. Therefore, using css() will always be false until you explicitly set an inline style on the element. I have never needed to find the computed background style but searching how to find computed styles should lead you in the proper direction. I don’t believe jQuery itself has a utility function for doing so but I might be wrong.
I ran some tests and found that jQuery convert color names and hex values into RGB there for you won’t see the result your looking for, see the below link as the best solution i found is to convert the RGB value into a HEX value.