Skip to content

Instantly share code, notes, and snippets.

@yckart
Last active December 29, 2022 12:16
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save yckart/5563717 to your computer and use it in GitHub Desktop.
Save yckart/5563717 to your computer and use it in GitHub Desktop.
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));
@hugodias
Copy link

hugodias commented Nov 7, 2015

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
Copy link

iErik commented Mar 8, 2016

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

@beauhaus
Copy link

This is brilliant. liked subscribed, followed, etc.

@badabingbreda
Copy link

Excellent, just what I needed! Thanks.

@mateushnsoares
Copy link

jQuery ? kkk I think that now you can remove the JQuery integration and modernize the JS

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