Skip to content

Instantly share code, notes, and snippets.

@vnys
Last active August 29, 2015 14:15
Show Gist options
  • Save vnys/0cef8aefbe52ccdaeaee to your computer and use it in GitHub Desktop.
Save vnys/0cef8aefbe52ccdaeaee to your computer and use it in GitHub Desktop.
inline styles in javascript
/*
Quick and easy way to write inline styles in js
setAttribute is not used to avoid overwriting the styles attribute if present on the element
Implies you’re inside a constructor where this.el is the element to be styled
*/
var styles = [
['width', '100%'],
['height', '100%'],
['background', 'orange']
];
// with arrow functions this refers to the enclosing context
styles.forEach( style => this.el.style[style[0]] = style[1]);
// without arrow functions this refers to the caller unless we change the scope with bind or the old «var self = this»
styles.forEach(function(style) {
this.el.style[style[0]] = style[1];
}.bind(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment