Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the background color of a class using jquery?

Tags:

jquery

css

I have set the background color of a class using css, now I want to put it in a variable using jquery. Thanks

like image 715
halocursed Avatar asked Jan 28 '10 21:01

halocursed


Video Answer


3 Answers

You may have to apply that class to a temporary element, and then extract the bgcolor of that element.

.cm { background-color:#990000 }

--

// creating an empty element and applying our class to it
var bgcolor = $("<div>").appendTo("body").addClass("cm").css("background-color");
alert(bgcolor); // rgb(153, 0, 0)
like image 140
Sampson Avatar answered Oct 23 '22 20:10

Sampson


If there is an element on the page using that class, you can do something like:

var backgroundColor = $('.classname').css('background-color');

But if nothing is using the class, I'm not familiar with any way to grab the color save from loading the .css file and parsing it in JavaScript (less than ideal).

like image 36
CalebD Avatar answered Oct 23 '22 20:10

CalebD


The problem is that jquery can't traverse the actual stylesheet (as far as I know), so if you have an element with two classes, you would have no way of knowing whether the color it returned was for the class you wanted or the other one. For instance:

.big { background-color: yellow; }

.mean { background-color: blue; }

The first one would be blue, but if you request the background color using:

 $(".big").css("background-color");

You would get blue, even though that class is set to yellow, since the first element is technically of the class big but it has a blue background.

I like Jonathan Sampson's idea. Create an element, make it invisible or offscreen, but give it an ID and the class you are wondering about. Then check the background color of that ID instead of checking by class:

 $("#colortest").css("background-color");
like image 1
Anthony Avatar answered Oct 23 '22 19:10

Anthony