css-style-guide
css-style-guide copied to clipboard
JS dependent styles
In the guide you mention that JS should only touch data attributes or classes starting with .js-
and that:
You shouldn't style those classes: they are to be used for Javascript purposes only.
When this interaction is simply a way for JS to handle some sort of JS-only state then I agree completely :smile:
What if the state change means that the element should be styled differently however? How do you propose handling that?
@Maximilianos In that case, we use BEM modifier classes (e.g. .control--important
). It's a different idea: js- classes are used as hooks to attach functionality to widgets, BEM modifier classes are toggled based on given criteria.
Ok, good. That's what I do too. (I've opened this issue because it's something that's troubled me while developing)
But, how do you handle the cases where you have one re-usable bit of JS and you want it to work with a bunch of Blocks?
For example, let's say you have a few blocks like control
, menu
, footer
and when you click on one you want to add an active class to it so that you can style it differently. (This is a simple example just to illustrate the issue).
The JS code you have, attaches itself to the [data-toggleable]
selector and handles adding or removing the active class for each element. You want your CSS to not know about your JS and you want your JS not to know about your CSS (within reason). So how do you add the correct control--active
or menu--active
classes?
I've been using the following as a solution to this:
/**
* Assuming the first className of
* the given element is its base
* className, return it
*
* @param element
* @returns {*}
*/
export function getBaseClassName(element) {
return !!element.classList && element.classList[0];
}
/**
* Return a BEM className for
* the given element with the
* given modifier
*
* @param element
* @param modifier
* @returns {*}
*/
export function getBEMModifier(element, modifier = 'active') {
const baseClassName = getBaseClassName(element);
return !!baseClassName && `${baseClassName}--${modifier}`;
}
So for <div class=“foo foo—bar left top”></div>
, getBEMModifier(div, ‘baz’)
would return foo—baz
.
Is this similar to what you do? How do you solve this? Thanks and sorry for the long post!
@Maximilianos That's a tricky one. I think this is where utility state classes come in handy. For states that can be common between blocks, we try to use .is-active
instead of .block--active
. This applies to states like active, disabled, hover, expanded etc. We then reserve BEM modifier classes for bespoke cases (like .modal--dark
). So you only have to add a single class in your JS code, not cater for different blocks.