6

I have a CSS class defined, call it:

<style type="text/css">
.Foo { position: fixed; left: 50px; top: 50px; }
</style>

where I position an element on the screen absolutely. Throughout my web page's execution, I create and delete many elements and give them class Foo. When I resize the browser, I want to change the left and top values on the Foo class so the position of all Foo elements is changed as a result of a calculation.

I don't want to simply change stylesheets, I want to calculate a value and make all current and future Foo elements have that new calculated left and top value.

This site has an example, but the code's quite complex. http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html

Is there a good, clean way to basically programmatically alter what Foo is defined as?

Thanks!

Levi Lindsey
  • 1,049
  • 1
  • 10
  • 17
Mike
  • 5,560
  • 12
  • 41
  • 52

1 Answers1

4

I think this is what you want:

<script>
var style;
function changeFoo(left, top) {
    if(typeof style == 'undefined') {
        var append = true;
        style = document.createElement('style');
    } else {
        while (style.hasChildNodes()) {
            style.removeChild(style.firstChild);
        }
    }
    var head = document.getElementsByTagName('head')[0];
    var rules = document.createTextNode(
        '.Foo { left: ' + left + 'px; top: ' + top + 'px; }'
    );

    style.type = 'text/css';
    if(style.styleSheet) {
        style.styleSheet.cssText = rules.nodeValue;
    } else {
        style.appendChild(rules);
    }
    if(append === true) head.appendChild(style);
}
</script>

This code was modified from an answer provided in this question which is very similar to what you asked. Whenever you need to change the position of all .Foo elements, you can just call changeFoo(newLeftValue, newTopValue); - the first time around it will create the <style> element and add it to the <head> of the document. Subsequent calls will just empty the <style> element that was already added and add the new rule.

Community
  • 1
  • 1
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • I think this will work, but the drawback is if Foo changes frequently, say, 100 times - there'll be 100 definitions for Foo on the page (with the cascading effect causing the latest one to take effect). I don't see that being good for performance. – Mike Feb 24 '09 at 02:35