Create a CSS rule / class with jQuery at runtime

Usually I have a CSS file which has the following rule:

#my-window {
    position: fixed;
    z-index: 102;
    display:none;
    top:50%;
    left:50%;
}

How can I avoid creating such a static CSS file by adding the CSS information during runtime actions to the body, or something similar? (only using jQuery)

I want to define it once but with jQuery and use it many times later; that's why I do not want to add it each time to the specific DOM elements.

I know the simple features (css("attr1", "value");), but how can I create a complete reusable CSS rule?


Solution 1:

You can create style element and insert it into DOM

$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");

tested on Opera10 FF3.5 iE8 iE6

Solution 2:

Simply

$("<style>")
    .prop("type", "text/css")
    .html("\
    #my-window {\
        position: fixed;\
        z-index: 102;\
        display:none;\
        top:50%;\
        left:50%;\
    }")
    .appendTo("head");

Noticed the back slashes? They are used to join strings that are on new lines. Leaving them out generates an error.

Solution 3:

you can apply css an an object. So you can define your object in your javascript like this:

var my_css_class = { backgroundColor : 'blue', color : '#fff' };

And then simply apply it to all the elements you want

$("#myelement").css(my_css_class);

So it is reusable. What purpose would you do this for though?

Solution 4:

You can use insertRule if you don't need to support IE < 9, according to dottoro. There's a bit of cross browser code over there as well.

document.styleSheets[0].insertRule('#my-window {\
    position: fixed;\
    z-index: 102;\
    display:none;\
    top:50%;\
    left:50%;\
}', 0)

Solution 5:

Here is a jquery plugin that allows you to inject CSS:

https://github.com/kajic/jquery-injectCSS

Example:

$.injectCSS({
    "#my-window": {
        "position": "fixed",
        "z-index": 102,
        "display": "none",
        "top": "50%",
        "left": "50%"
    }
});