Create a gist now

Instantly share code, notes, and snippets.

Add css-rules to an existing stylesheet - http://stackoverflow.com/a/16507264/1250044
/*!
* jquery.addrule.js 0.0.2 - https://gist.github.com/yckart/5563717/
* Add css-rules to an existing stylesheet.
*
* @see http://stackoverflow.com/a/16507264/1250044
*
* Copyright (c) 2013 Yannick Albert (http://yckart.com)
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
* 2013/11/23
**/
(function ($) {
window.addRule = function (selector, styles, sheet) {
styles = (function (styles) {
if (typeof styles === "string") return styles;
var clone = "";
for (var prop in styles) {
if (styles.hasOwnProperty(prop)) {
var val = styles[prop];
prop = prop.replace(/([A-Z])/g, "-$1").toLowerCase(); // convert to dash-case
clone += prop + ":" + (prop === "content" ? '"' + val + '"' : val) + "; ";
}
}
return clone;
}(styles));
sheet = sheet || document.styleSheets[document.styleSheets.length - 1];
if (sheet.insertRule) sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
else if (sheet.addRule) sheet.addRule(selector, styles);
return this;
};
if ($) $.fn.addRule = function (styles, sheet) {
addRule(this.selector, styles, sheet);
return this;
};
}(this.jQuery || this.Zepto));
@yckart
Owner
// add some styles as object notation
$("body:after").addRule({
    content: "foo",
    color: "red"
});

// or as string (note, you've to write the properties in dash-case)
$("body:after").addRule("font-size: 23px");

// or plain, without jquery
addRule("body:after", "font-style: italic");

http://jsfiddle.net/ARTsinn/bNkfP/

@corysimmons

Keep getting Uncaught TypeError: Cannot read property 'length' of null on line 30

@corysimmons

Removing that line fixed it.

@corysimmons
  /*!
   * jquery.addrule.js 0.0.1 - https://gist.github.com/yckart/5563717/
   * Add css-rules to an existing stylesheet.
   *
   * @see http://stackoverflow.com/a/16507264/1250044
   *
   * Copyright (c) 2013 Yannick Albert (http://yckart.com)
   * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
   * 2013/05/12
   **/

  (function ($) {
    window.addRule = function (selector, styles, sheet) {
      if (typeof styles !== "string") {
        var clone = "";
        for (var style in styles) {
          var val = styles[style];
          style = style.replace(/([A-Z])/g, "-$1").toLowerCase(); // convert to dash-case
          clone += style + ":" + (style === "content" ? '"' + val + '"' : val) + "; ";
        }
        styles = clone;
      }
      sheet = sheet || document.styleSheets[0];
      sheet.addRule(selector, styles);
      return this;
    };
    if ($) {
      $.fn.addRule = function (styles, sheet) {
        addRule(this.selector, styles, sheet);
        return this;
      };
    }
  }(window.jQuery));

This works

Update Discovered it wasn't working because I wasn't running on localhost. Use the 0.0.2 Gist and run python -m SimpleHTTPServer then navigate to localhost:8000 for a quick fix.

It's a security thing. Same thing happens if you expect protocol-less files (like Google's jQuery CDN) to work in file:/// context.

@corysimmons

Having trouble with looping over .each within jQuery and adding rules to $(this). Any ideas?

Update Nevermind, sorry to make you check this. I had to iterate over it and do a bunch of nth-child hackery. Works now. Thanks!

@yckart
Owner

@corysimmons Thanks for the great suggestions. Didn't noticed that adding custom css-rules result in a security thing. I’ll roll up this piece of code next week and try to fix some things. Thanks again for your investigation! :-)

@nightbook

@yckart you're a life saver, thank you for this. Works like a charm, I'm using it in a resize function to readjust the height of a psuedo dynamically. Only question I had was it adds elements constantly is there anyway to clean up the previously added rules maybe with an additional removeRule call?
Thank you

@hugodias

I'm actually getting the following error:
Failed to parse the rule ' { background-image: http://192.168.56.10/wp-content/uploads/2015/06/tuscany-landscape_087-3840x350.jpeg }'.

Any ideas?

Edit: My mistake, the ":before" was missing on my call 😢

@iErik

That's a great function. Is there any way to remove a previously applied ':after' style?

@LeoFib

This is brilliant. liked subscribed, followed, etc.

@badabingbreda

Excellent, just what I needed! Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment