user834595
user834595

Reputation:

Removing/Replacing dynamically created <STYLE> tags (using jQuery)

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! :)

Upvotes: 0

Views: 1096

Answers (2)

adeneo
adeneo

Reputation: 318192

This is'nt really a common technique at all, you'd be better of just setting the styles directly on the elements :

$('.tilewidth').css({
                     width:  tilesize+'px',
                     height: tilesize+'px'
                   });

that way the elements styles will be updated on resize instead of adding a bunch of style tags.

Upvotes: 1

Robin Whittleton
Robin Whittleton

Reputation: 6339

Give your style tag an id and remove it? E.g.

$('#sizing').remove();
$('<style id="sizing">…</style>').appendTo('head');

Actually, second thoughts, you’d be better off just setting the text rather than creating an element over and over again.

var sizing = $('#sizing');
if (sizing.length) {
  sizing.text('my new styles');
} else {
  $('<style id="sizing">…</style>').appendTo('head');
}

Upvotes: 1

Related Questions