'How to use CSSStyleSheet.insertRule() to change a :root property
I am trying to set the background color of the :root css property in my html file based off a hash in the url. The attached code works, but the hash doesn't persist through page changes on the site. I'm thinking that I can use CSSStyleSheet.insertRule() to make the css change persist since each page uses the same stylesheet, but I'm not sure how to properly use the function.
<script>
if (window.location.hash) {
document.documentElement.style.setProperty(
'--main-bg-color',
window.location.hash
)
}
</script>
Solution 1:[1]
This sort of works for me. I don't know if it will work in all browsers, I only tried chrome and firefox:
<html>
<head>
<style>
:root { --main-bg-color: red }
body { background-color : var(--main-bg-color) }
</style>
<script>
if (window.location.hash) {
let hashValue = window.location.hash;
let tagName = '--main-bg-color';
document.documentElement.style.setProperty( tagName, hashValue);
let newRule = ':root { ' + tagName + ':' + window.location.hash + ';}';
let nextRoot = document.styleSheets[0].cssRules.length ;
alert(tagName + ': ' + hashValue + "\n" + '#' + nextRoot + ' ' + newRule);
document.styleSheets[0].insertRule (newRule, nextRoot)
}
</script>
</head>
<body>
this should turn the background color from red to whatever value is in the hash.
</body>
</html>
i believe the solution (for now) is to insert a new rule, but make sure the new rule has the highest priority number. you could also determine the current :root
value, parse it out, and make changes there as well.
I have not seen any javascript calls to manipulate CSS rules except for insertRule
and removeRule
, or if something like that exists, I missed them. I did look through document.styleSheets[0].cssRules[0]
and all I could find was cssText
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | E_net4 - Krabbe mit Hüten |