Best way to share constants between Javascript & CSS
If the "constant" corresponds to some parameter that can be ready from an element, then in your javascript startup you can read that element. For example, if what you care about is the width of some element with id="foo" you could use (assuming jquery)
$('#foo').width()
or
$('#foo').css('width')
But for more complex sets of global variable, I've started using a hack of embedding stuff as strings in the background-image attribute of a hidden div. This works because you can put just about anything in a background-image string. And then in javascript startup I can read that string from background-image on that div and decode it to javascript.
For example, I have a .less file with these "constants"
@hide-time: 450;
@hide-final-width: 40;
and in that .less file I use these for this div
#css-shared-globals {
background-image: url("about:$$$({hideChatTime:@{hide-chat-time},hideFinalWidth:@{hide-final-width}})$$$");
display:none;
}
in the related .html file is this otherwise-useless div:
<div id="css-shared-globals" style="display:none;"></div>
and finally in .js I can read the shared global constant from that hidden div with this startup code:
// load globals from chat.less
var el = $('#css-shared-globals');
var elObj = eval(decodeURI(el.css('background-image').split('$$$')[1]));
hide_time = elObj.hideChatTime;
hide_final_width = elObj.hideFinalWidth;
The result of the whole kludge is that my .less (or .css) and .js files are seeing the same constants and I only need to change them in one place (the less or css file). It's a mess but, so far, it works.
Is there a good way to have a "single place" for constants like this?
The stylesheet.
Then dynamically set class names.
(At least in many cases. We don't know the specifics of your problem)