Sometimes I have to add CSS styles to the DOM programmatically (if you need a reason: imagine that you are writing a small ui widget that comes with its own style, but should consist of only one * .js file to simplify processing). In this case, I prefer to define a style in my script code with a musical notation of the object instead of a single large line that mixes the rules, properties and markup.
var thumbHoverStyle = { "background-color": "rgba(211, 211, 211, 0.5)", "cursor": "pointer" };
vs
var thumbHoverStyle = "<style> .thumb:hover { background-color: rgba(211, 211, 211, 0.5); cursor: pointer; } </style>";
Such a css object can be easily used with the JQuery.css () function , but the problem starts as soon as I want a style a css pseudo-class (in my example: hover). In this case, I cannot use the JQuery .css()
function, and I return to inserting the appropriate style tag into my DOM.
var thumbHoverStyleTag = toStyleTag( { ".thumb:hover": thumbHoverStyle } ); _root.append(thumbHoverStyleTag);
I googled and stackoverflowed but could not find a utility function that converts my css object to a style tag. In the end, I wrote my own function (and I probably provided it as an answer to this question), but I still want to know if there is a library function for this. What is the most elegant way to do this?
Edit
My implementation in TypeScript:
function appendPxIfNumber(value: any): string { return (typeof value === "number") ? "" + value + "px" : value; } function toStyleTag(rulesObj: any) { var combinedRules: string = ""; for (var selector in rulesObj) { var cssObject = rulesObj[selector]; var combinedProperties = ""; for (var prop in cssObject) { var value = cssObject[prop]; combinedProperties += `${prop}: ${appendPxIfNumber(value)};` + "\n"; } combinedRules += ` ${selector} {${combinedProperties}}` + "\n"; } return $(`<style>${combinedRules}</style>`); }
Usage example:
var styleTag = toStyleTag( { ".thumb": thumbStyle, ".thumb:hover": thumbHoverStyle } );