Jonathan Neal tweeted a heck of slightly CSS trick the opposite day, placing JSON inside CSS and plucking it out with JavaScript. Legitimate values for customized properties are fairly liberal! So this seems for a CSS rule (e.g. a complete block, like #x { y: z; } the place the cssText begins with — (which isn’t a sound selector, however who cares — you can change it if you wish to thisIsJson or one thing) after which slices out a string that JSON.parse() works on.
I re-typed his instance right here:
Is this convenient?
WELL.
Most likely not, like, each day. However keep in mind that JSONP continues to be a factor as a result of CORS exists. Chucking some JSON in CSS I might suppose is one other approach round CORS. I kinda doubt it can catch on, but it surely’s attainable. Bear in mind not way back we had been speaking about utilizing CSS as an API for literal information. One other questionable concept. 😉
I feel “placing bizarre stuff in customized properties” is the brand new “placing bizarre stuff in CSS content material.”
For instance, ya know the way there are media queries in JavaScript, à la matchMedia? And, after all, there are media queries in CSS, too. There was a time (and I’m undecided it’s handed) the place defining these media queries solely as soon as felt like a good suggestion, so we weren’t sustaining media queries in a number of locations. To maintain them “in sync” one concept was to outline them in CSS and have them swap the worth of some CSS content material (e.g. @media (max-width: 500px) { physique::after { content material: “max500”; show: none; } }) then actually look ahead to that content material to vary with JavaScript — and also you’d know that media question was lively. For actual! No joke!
And talking of JSON in CSS, you possibly can chuck straight-up JavaScript in there as effectively. This isn’t as intelligent as Jonathan’s extraction as a result of it simply yanks the worth out and evals it.
Caleb Williams made a Internet Employee with CSS.
The put up JSON in CSS appeared first on CSS-Tips.
You may help CSS-Tips by being an MVP Supporter.
Subscribe to MarketingSolution.
Receive web development discounts & web design tutorials.
Now! Lets GROW Together!