Parse CSS into JavaScript with selector awareness - javascript

I want to build something that could consume a .css file return a function that would take an array of class names and return the styles that would apply to an element with those class names, as a JavaScript object. (Such an tool would be suitable for use with Glamor, Fela, or other CSS-in-JS technologies.)
E.g., if you have this CSS file:
.btn {
border: 1px solid gray;
}
.btn.primary {
background: blue;
border-color: blue;
}
.btn-group {
display: inline-block;
}
then you could do something like this:
import css from "./btn.css";
import applicableStyles from "applicable-styles"; // what I want to build
const btnStyles = applicableStyles(css, ['btn', 'primary']);
// Expected value:
{
border: "1px solid gray"
background: "blue";
border-color: "blue";
}
In this example, .btn-group gets ignored because we only asked what style would apply to .btn.primary.
This is new territory for me, but I know there are tools out there for parsing CSS. What libraries might be most promising to take a look at? (Or, does something like this exist already?)

This should be possible using some of the various npm packages out there.
For example, the css-object-loader package allows you to require a .css file, which is converted to an object with keys corresponding to the selectors, which you can then access.
p {
font-size: 14px;
}
h1 {
text-indent: 20px;
}
.centered {
width: 100%;
margin: 0 auto;
}
var selectors = require('./rules.css');
// Get the
selectors['.centered']
I've also seen SCSS destructured at import, like:
import {btn, primary} from './btn.scss';
but unfortunately I can't remember what loaders were used to do this.

Related

Using dark or light mode

what is the best way to incorporate something like this into my site? I've tried using plugins but I cant get it to work. Doesn't have to be fancy.
Does anyone have it or have used one in the past they can recommend? Otherwise, is there a way to code it using JavaScript?
You could just set a button to trigger a boolean for example and based on its values, change the background-color of the items you want to change into dark mode.
I personally used react context for this one, something like this (kinda perfect how they used theme as an example). You should study it.
It depends on your framework, but if you use Material-UI, it has this option.
you can change palette type from light to dark and vice versa to achieve your requirements. Take a look here.
But if you don't use any framework, you should make a css structure that has two classes, light and dark, have some properties like color and background color and etc., and when the toggle theme button clicked, you will change all your classes from light to dark for example, also you can use animation for the effects.
There is a multiple solutions for this problem, if you are using a specific framework I suggest you check if there a way to do it with it, if you are not using any framework you still have multiple solutions and I suggest to create for each element you want to change his properties to dark mode another CSS class for each one, and with JavaScript create a function (that can call by a button on the html) that change all the element you want to those external classes, and if you click this button once again is reverse the function and make all the classes be with the original CSS classes
Maybe this should help you to kickstart.
<html class="theme-light">
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.theme-light {
--color-primary: #0060df;
--color-secondary: #fbfbfe;
--color-accent: #fd6f53;
--font-color: #000000;
}
.theme-dark {
--color-primary: #17ed90;
--color-secondary: #243133;
--color-accent: #12cdea;
--font-color: #ffffff;
}
.container {
display: flex;
width: 100%;
height: 100%;
background: var(--color-secondary);
flex-direction: column;
justify-content: center;
align-items: center;
}
.container h1 {
color: var(--font-color);
}
.container button {
color: var(--font-color);
background: var(--color-primary);
padding: 10px 20px;
border: 0;
border-radius: 5px;
}
</style>
<script>
// Set a Theme
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.documentElement.className = themeName;
}
// Toggle From light and dark theme and Vice-Versa
function toggleTheme() {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-light');
} else {
setTheme('theme-dark');
}
}
// Onload Theme
(function() {
if (localStorage.getItem('theme') === 'theme-dark') {
setTheme('theme-dark');
} else {
setTheme('theme-light');
}
})();
</script>
<body>
<div class="container">
<h1>Theme Switcher</h1>
<button id="switch" onclick="toggleTheme()">Switch Theme</button>
</div>
</body>
</html>
This is a simple approach that I've used several times:
On the main html file, I load the default theme, for example the light one:
<link rel="stylesheet" href="/themes/light/theme.css" id="linkTheme" />
Then, on the theme changer button/menu option, I change the CSS file of the above link to load the corresponding one, something like:
const handleToggleTheme = (dark) => {
const lightUrl = "/themes/light/theme.css";
const darkUrl = "/themes/dark/theme.css";
if (dark) {
document.getElementById('linkTheme').setAttribute('href', darkUrl);
}
else {
document.getElementById('linkTheme').setAttribute('href', lightUrl);
}
}

Change Element's Class Name without affecting CSS values

I have an DOM element and I want to only change the className of the element. I want to remain the css values as it. (For both external css and inline css)
For example, if I have this:
.sample{
display: block
font-size: 10px,
font-color: #fff
}
<div class="sample">...</div>
After doing some JavaScript operation I need to reach this:
.newCss{
display: block
font-size: 10px,
font-color: #fff
}
<div class="newCss">...</div>
Note: There is no strict rule for css, there can be a css selector with 100 values or with only 1 one.
Note2: There is no css selector such as .newCss, I should transform the css properties from .sample, to a new one called .newCss
You can get the computed style for the element prior to making the change:
const style = getComputedStyle(theElement);
and then apply that styling to the element directly:
theElement.style.cssText = style.cssText;
Then removing the class won't change the element's styling, because it's styled inline.
Example:
const theElement = document.querySelector(".sample");
console.log("before:", theElement.className);
setTimeout(() => {
const cssText = getComputedStyle(theElement).cssText;
theElement.className = "newCss";
theElement.style.cssText = cssText;
console.log("after: ", theElement.className);
}, 800);
.sample{
display: block;
font-size: 10px;
color: #fff;
background-color: black;
}
.newCss {
background-color: yellow;
}
<div class="sample">this is the div</div>
If the new class has styling associated with it in CSS, that might affect the styling of the element. If you need to prevent that, change the class first, then assign the CSS text:
Example:
const theElement = document.querySelector(".sample");
console.log("before:", theElement.className);
setTimeout(() => {
theElement.style.cssText = getComputedStyle(theElement).cssText;
theElement.className = "newCss";
console.log("after: ", theElement.className);
}, 800);
.sample{
display: block;
font-size: 10px;
color: #fff;
background-color: black;
}
<div class="sample">this is the div</div>
You have to use JavaScript. In order to use JavaScript, you have to assign a ID to the <div> tag. Then manipulate it by JavaScript. Example: document.getElementById("id1").className="sample";
Also make sure that you using semicolon(;) after CSS properties.
function f1()
{
document.getElementById("id1").className="sample";
}
.sample{
display: block;
font-size: 10px;
font-color: #fff;
color: red;
}
.newCss{
display: block;
font-size: 10px;
font-color: #fff;
color: green;
}
<div id='id1' class="newCss"><p>Hello</p></div>
<button onclick="f1()">Click</button>
Well, if you want to change className to a class which is identical, you can simply redefine the class in the style sheet to be equivalent, or you can use inline styles, but the purpose of CSS classes is to keep a unique set of rules, so two identically-ruled CSS classes would defeat the purpose for which they exist, to be unique definitions of CSS rules, so if you want the CSS rules exactly the same, then there wouldn't be a reason to change the className, unless you were referencing it with other JavaScript functions, or if you wanted to add additional styles while keeping the old ones, in such a case:
use classList to dynamically add or remove certain individual classes, while keeping others.

Is it possible to assign a class to :root?

As I am thinking about solutions to another problem of mine, I am trying to understand to which extend CSS elements can inherit from other elements. Specifically, having the following definition
.dark {
background-color: black;
}
.light {
background-color: white
}
is it possible to programmatically assign (with JS, probably) one of these classes to the :root element?
It can be done easily with JS.
Select the element:
const root = document.querySelector(':root')
Assign the class to it:
root.classList.add('light')
All together:
const root = document.querySelector(':root')
root.classList.add('light')
Or, instead of having two classes, it might be better to have a :not() selector:
:root:not(.dark){
background-color: white;
}
:root.dark{
background-color: black;
}
I would use (and have used) CSS variables for this.
:root {
--background-color: black;
}
.background {
background-color: var(--background-color);
}
Then change the CSS variable with javascript.
In HTML, :root is equivalent to <html> (doc):
In HTML, :root represents the element and is identical to the
selector html, except that its specificity is higher.
A possible solution would be to apply the class to <html>:
document.getElementsByTagName("html")[0].classList.add('dark')
.dark {
background-color: red;
}
<html>
hello
</html>

How do I check for CSS styling with JavaScript?

Why am I unable to test for CSS styling like this:
if (document.getElementById("myText").style.outline == "10px solid black")
{
// Do something
}
or
if (document.getElementById("myText").style.match("outline: 10px solid
black"))
{
// Do something;
}
when I have:
#myText
{
outline: 10px solid black;
}
I assume getComputedStyle will help in finding the applied style
var elem1 = document.getElementById("myText"),
style = window.getComputedStyle(elem1, null);
console.log(style.outline)
#myText {
outline: 10px solid black;
}
<div id="myText">Text</div>
The style property will only return styles that are set on the element's style attribute or in javascript, so you won't see styles that applied separately by CSS.
Furthermore, there are multiple ways of expressing the same set of CSS properties, and the browser is generating a string that describes the current properties (rather than returning whatever string you used to set them). Therefore the browser can and will reorder the property values and/or convert them to other units (e.g. black -> rgb(0,0,0)) so testing for a particular string is never going to be reliable. E.g.
document.body.style.outline = "10px solid black"
console.log(document.body.style.outline)

javascript: insert large CSS string in one go, into every DOM element

This is a two part question - first I need to get every element that is a child (or subchild, etc) of a parent element, and then I need to reset it's style. As such, I'm looking to do something like the following:
var everything = parent.getEveryElementBelowThisOne();
for (i=0; i<everything.length; i++)
everything[i].css = "font: 100%/100% Verdana,Arial,Helvetica,sans-serif; color: rgb(0, 0, o); margin: 0px; padding: 0px; border-collapse: collapse; border-width: 0px; border-spacing: 0px; text-align: left; outline: 0pt none; text-transform: none; vertical-align: middle; background-color: transparent; table-layout: auto; min-width: 0px; min-height: 0px;"
So my questions are as follows:
Is there a javascript function that will effectively walk through the DOM below a given element?
Is there a javascript function that will let me set a CSS string like that? Or do I have to have a whole bunch of entries like:
everything[i].style.font = ...;
everything[i].style.color = ...;
[...]
everything[i].style.min-height: ...;
jQuery is not an option.
Instead of a string, I would use an object, much more readable and maintainable:
var new_css = {
font: '100%/100% Verdana,Arial,Helvetica,sans-serif',
color: 'rgb(0, 0, o)',
margin: '0px',
padding: '0px',
borderCollapse: 'collapse'
/* rest here ... */
}
Then use a helper function, something like:
function setStyle (element, style) {
for (var n in style) {
element[n] = style[n];
}
}
and into your for loop:
for (i=0; i<everything.length; i++) setStyle(everything[i],new_css);
A note about the setStyle function (before people downvote me for this like last time), I purposely did not use a hasOwnProperty to check the elements of style because in this case, and in most cases we are using an object not inherited from anything. If you construct your new_css object any other way or if you use a library (prototype, I'm looking at you) that modify Object's prototype which may cause problems then feel free to add the hasOwnProperty check. Anyway, setting nonexistent style values are mostly harmless. And without a hasOwnProperty check you can use inheritence to compose style objects.
Use myElement.style.cssText:
var everything = parent.getEveryElementBelowThisOne();
for (i=0; i<everything.length; i++)
everything[i].style.cssText = "font: 100%/100% Verdana,Arial,Helvetica,sans-serif; color: rgb(0, 0, o); margin: 0px; padding: 0px; border-collapse: collapse; border-width: 0px; border-spacing: 0px; text-align: left; outline: 0pt none; text-transform: none; vertical-align: middle; background-color: transparent; table-layout: auto; min-width: 0px; min-height: 0px;"
But note that this will override any inline style attributes already applied. To append extra inline css you should use:
myElement.style.cssText += '; color:red; ...'; // note the initial ";"
Its slightly offbeat, as when you talk of parent, we assume you would be considering its children at some point. But when you say, every element below this one then they may be DOM elements after the concerned element. Yours may be either of the case.
I assume you want to change style of next element siblings.
Using raw javascript, you can traverse in a generic looping way, as
nS = parent.nextElementSibling
while(nS){
nS.style.width = '100%';
// Change the desired style here
// You can also further loop on nS's children using `nS.childNodes`,
// if you want to change their styles too
nS = nS.nextElementSibling;
}
As you can see with raw javascript, the way to change styles is quite repelling.
On the other hand, jQuery gives good DOM feature.. including easy traversing, even styling.
Like, the same thing in jQuery would be.
$(parent).nextAll().each(function(){
$(this).css({'width': '100%', 'other': 'rules', 'as': 'one-dict'});
// Change the desired style here
// You can also further loop nS's children using `$(this).children()`,
// if you want to change their styles too
});
Hope this helps.

Categories