I’m using a common technique to create <STYLE>s from within my JavaScript/jQuery – much like this
$('<style>.tilewidth { width:' + tilesize + 'px; height: ' + tilesize + 'px;}</style>').appendTo('head');
I’m doing this to control how certain objects scale (forcing DIVs to be square for example) – and it’s working fine.
Problem is I rerun the code if the window is re sized – at which point it inserting a new set of <STYLE> tags after the existing ones (if someone drag-stretch/shrinks a window it could insert 100s!!)
This works, I should emphasize, because CSS only reads the last entries – but it seems clumsy and nasty and messy and untidy and horrible (it makes reading code in Firebug near impossible!!)
Question is – can I remove the old tags before inserting the new ones – or should I just force a complete page reload in re size (and if so, how – and won’t it be a performance drain)?
Update: as per Robin’s answer, I created a function something like this
function addStyle(sname,scode) {
scode = "." + sname + " {" + scode + "}";
if ($("#style-" + sname).length)
$("#style-" + sname).html(scode);
else
$("<style/>").attr("id","style-"+sname).html(scode).appendTo("head");
}
Which works pretty well – thanks! 🙂
Give your
styletag anidand remove it? E.g.Actually, second thoughts, you’d be better off just setting the text rather than creating an element over and over again.