views:

48

answers:

1

I want to defined a variable/parameter in CSS and access it by javascript. What is the best way of doing this?

One option I thought of would be to place a cutsom attribute on the body element, then access that attribute via jQuery.

A little more info: I'm defining colour sets in CSS. I've created a function with RaphaelJS to draw a gradient background on the page. I want this function to use a highlight colour (which is not used elsewhere on the DOM) which will be defined in the CSS along with the other colour elements.

Thanks

+2  A: 

Create a mock element using jQuery, assign the class hightlightColour to it, get any CSS definitions you might need and destroy the element.

$(function() {
    var highlightColour = getClassCSS('highlightColour', 'color');
    alert(highlightColour);
});

function getClassCSS(className, attribute) {
    var mock = $('<div />').addClass(className).appendTo('body');
    var value = mock.css(attribute);
    mock.remove();
    return value;
}

That snippet would get the color attribute that is defined for the highlightColour class in CSS. Just make sure there's nothing overwriting the attributes. Tested and working on Firefox 3.6.

Tatu Ulmanen
this doesn't work, as is, because `mock` will only take on the properties when attached to the DOM. (tested safari).
Ross
@Ross, you're right, you need to attach the element to the DOM first. I've updated my answer.
Tatu Ulmanen