Question / TLDR
How would I name a CSS property so that
- it can be picked up by javascript (e.g.
window.getComputedStyle(element), orjQuery.fn.css()) as the currently active style on an element, but - it has no effect on how content is displayed?
- (EDIT: Ideally it should have good cross-browser support and feel natural / not too arbitrary.)
Background / use case
I am programming a responsive tabs / accordion component. The component should ship with js and css. But the break point should be defined in site-specific CSS, that is, a CSS file outside of the package.
The idea:
Site-specific CSS contains a rule like this:
@media only screen and (max-width: 768px) {
// I want this CSS to feel natural, semantic, and memorable.
.supertabs {
__accordion: 1; /* This is ignored by the browser, see "Problem" below. */
}
}
In javascript I would pick this up like so:
// Use jQuery to make this code look simpler.
var $ = jQuery;
$(window).resize(function () {
$('.supertabs').each(function () {
// Won't work, because '__accordion' is not a known CSS property name.
if (window.getComputedStyle(this).__accordion) {
// Enable accordion.
$(this).addClass('supertabs-accordion');
$(this).removeClass('supertabs-tabs');
}
else {
// Enable tabs.
$(this).removeClass('supertabs-accordion');
$(this).addClass('supertabs-tabs');
}
});
});
Then the package CSS can pick this up and apply the change that distinguish accordion vs tabs behavior.
Problem:
The property name "__accordion" is unknown, ignored by the browser, and not accessible with getComputedStyle().
Alternatives I considered
I could use a known property name, but this might have an undesired effect.
I could use the "variable" syntax (--accordion), but technically this also has an effect, it is not picked up by getComputedStyle(), and I am not sure at all what Internet Explorer will do with it (we are supporting IE11, fyi).
I could introduce a hidden element and come up with a made-up convention, e.g. if the hidden element is position:absolute, then show the accordion, otherwise show tabs. The idea is similar to this article, https://www.lullabot.com/articles/importing-css-breakpoints-into-javascript.
The hidden element would work. But I was looking for something less arbitrary, to make this more suitable for a package to be published.
grid-gapis only considered if your element is setdisplay:grid. If you are sure you will never use CSS grid then you can use it. There is also other properties related to flexboxwindow.getComputedStyle(div).getPropertyValue('--example-var')['property-name']works only for known regular properties,.getPropertyValue()works for known properties and variables, and unknown non-variables are not accessible with either method.