Reputation: 2451
I'm currently writing a simple jQuery plugin where I need to insert around 30 to 40 rules into a single stylesheet tag, right now the current code I'm using was written by another StackOverflow user. It does the job, but it creates a separate style tag for each rule, how should I modify this code to get it all in one tag? (I'm still working on Javascript, so I don't fully understand the source.)
(
function( $ )
{
$.style={
insertRule:function(selector,rules,contxt)
{
var context=contxt||document,stylesheet;
if(typeof context.styleSheets=='object')
{
if(context.styleSheets.length)
{
stylesheet=context.styleSheets[context.styleSheets.length-1];
}
if(context.styleSheets.length)
{
if(context.createStyleSheet)
{
stylesheet=context.createStyleSheet();
}
else
{
context.getElementsByTagName('head')[0].appendChild(context.createElement('style'));
stylesheet=context.styleSheets[context.styleSheets.length-2];
}
}
if(stylesheet.addRule)
{
for(var i=0;i<selector.length;++i)
{
stylesheet.addRule(selector[i],rules);
}
}
else{
stylesheet.insertRule(selector.join(',') + '{' + rules + '}', stylesheet.cssRules.length);
}
}
console.log(selector + " { " + rules + " }");
}
};
}
)( jQuery );
Upvotes: 0
Views: 445
Reputation: 1
Try these (patterns)
$(function() {
var styles = "body{background:blue}"
+"div{color:#fff;}";
$("<style>", {
"id" : "styles",
"text" : styles
})
.appendTo("head");
var rules = ["span{color:red;font-size:24px;}", "em{background:gold;}"];
$.each(rules, function(index, value){
$("#styles").append("\n" + value);;
});
})
jsfiddle http://jsfiddle.net/guest271314/4MQyY/
Upvotes: 1