3

I'm writing a reusable Javascript snippet (jQuery plugin) that involves DOM CSS styling. Since it's supposed to be usable by anyone, I'd like to avoid conflicts between its CSS classes names and other existing classes on a document. That's why I'm using a namespace string as a prefix for all of its class names (e.g. class grid becomes prfx-grid if my prefix is prfx-). To respect DRY, and have it easily changeable, I'd like to declare my prefix only once, and access it from both the CSS spreadsheet (possibly using Sass) and the Javascript code. If possible, I'd also like to go on with only 2 files (my .js and my .css).

Is there a way to declare such a prefix/namespace constant so it can be accessed from both (S)CSS and Javascript ?

2 Answers 2

1

I don't know of an easy way to have it defined in only one place. It's simple enough to have it only defined in two places, though: once in the javascript and once in your SASS. In the javascript you can use a global variable (or however else you store your constant values), and in SASS you can define the prefix like this:

$prefix: 'prfx-';

.#{$prefix}grid {
    /* compiles to .prfx-grid */
}

.#{$prefix}other {
    /* and so on */
}

It may not be as nice as having a single definition across both the javascript and CSS, but changing in two places is certainly better than a global find-replace. Theoretically, you could probably add a Ruby extension to SASS that would read the prefix value out of a file that the Javascript code could access via AJAX, but it seems to me that such a system wouldn't be worth the extra effort to get it set up and working properly.

Sign up to request clarification or add additional context in comments.

Comments

0

You could define a pseudo-element and use the content property of CSS to transmit your SCSS prefix to JavaScript. I'm using <body> in this example but it could be any pseudo element:

$prefix: 'myPrefix';

body::after {
  // Value must be quoted, so we use
  // string interpolation to print variable
  content: '#{$prefix}';
}

Then JavaScript can look for this text at runtime and use it as a prefix:

// pseudos can't be selected like normal DOM elements due to
// browser specs, but you can grab computed styles and remove
// the quotes yourself.
var prefix = window.getComputedStyle(document.body, '::after').getPropertyValue('content').replace(/"/g,'');
// result: 'myPrefix'

The fetching of computed styles causes a reflow/layout/paint but if you're just doing this one time it's not the end of the world.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.