2

I want to dynamically set the height of an element .selected based on the screen height. $('.selected').css('height', height); and $('.selected').height(height); work but when another element becomes .selected it doesn't get affected by this rule.

What I really want to do is something like this:

var s = $('<style>.selected{height:'+height+'px}</style>').appendTo(document.head);
...
// change the height later
s.remove();
s = $('<style>.selected{height:'+new_height+'px}</style>').appendTo(document.head);

Is there a better way to do this?

2
  • 2
    No, that's the best way to do it. Note that it would be better to modify your existing style tag rather than to add a new one to override an existing rule, if possible. Feb 3, 2011 at 22:39
  • How about s.text('.selected{height:'+new_height+'px}'); ?
    – Jake
    Feb 3, 2011 at 22:44

1 Answer 1

1

You can use document.styleSheets[0].insertRule(".selected{height:"+new_height+"px}", 0); or similar. You can read more about manipulating stylesheets with insertRule here

In general tho, what you are doing is fine. If i was you i'd go with keeping a refrence to your style element tho and replace it with the new one like this:

var s = $('<style>.selected{height:'+height+'px}</style>').appendTo(head);
...
// change the height later
s.replaceWith('<style>.selected{height:'+new_height+'px}</style>');
2
  • @drachenstern: the remove statement wasn't in the question when i wrote my answer ;) Otherwise, by some kind of magic, I managed to copy/paste a block of code missing a single line in the middle... Feb 3, 2011 at 22:53
  • @drachenstern: I agree, it is an odd one, that I cannot explain by other means than magic copy/paste Feb 3, 2011 at 22:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.