Skip to content

Instantly share code, notes, and snippets.

Created February 2, 2011 12:54
Show Gist options
  • Save anonymous/807632 to your computer and use it in GitHub Desktop.
Save anonymous/807632 to your computer and use it in GitHub Desktop.
(function () {
var elCache = [];
var styleCache = [];
forceStyle = function (el, obj) {
if (elCache.indexOf(el) == -1) {
elCache.push(el);
styleCache.push(el.style.cssText);
}
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
el.style.cssText += ';' + prop + ':' + obj[prop] + ' !important';
}
};
};
restoreStyle = function (el) {
var index = elCache.indexOf(el);
if (index == -1) {
return;
}
el.style.cssText = styleCache[index];
elCache.splice(index, 1);
styleCache.splice(index, 1);
};
})();
// Example usage:
forceStyle(document.body, {margin: '10px', 'border-left': '2px solid red'});
restoreStyle(document.body);
@CollinChaffin
Copy link

Man as much as I appreciate other people sharing code, it really bothers me when people go so fast like this that they post "teaser" functions to answer a question that don't actually work because they aren't actually tested. Sorry, but I just had to spend as much time figuring out why your example syntax (all of it) won't work to the point that I've now just re-written the function.

FYI, how does this code: el.style.cssText += ';' + prop + ':' + obj[prop] + ' !important'; translate in any way to any of this: // Example usage: forceStyle(document.body, {margin: '10px', 'border-left': '2px solid red'});

Just start with the colon in your usage.......nope that's hard-coded with + ':' + and then the whole ability to even properly parse the darn CSS....which is it? This part of the example: {margin: '10px', seems to indicate we go with CSS obj no quotes followed by a colon no quotes but some reason quote the value. Nope code isn't written that way. How about the next part of the usage: , 'border-left': '2px solid red'} now it's quoted obj followed by a non-quoted colon then followed by a quoted value. Nope, code is not remotely written that way.

The upshot is, this was some in your mind wireframe of what this function "could" be but anyone hoping to use it should know it does NOT work as written and needs major rewriting to work as intended.

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