Rich-text Reply

Experiment CSS - JS2CSS helper function

casecode 05-15-15

Experiment CSS - JS2CSS helper function

Hello Optiverse. Just cross posting from our weekly engineering blog here at Clearhead. We came up with a little helper function to make it easier to write and append CSS in your JS files. Since Experiment CSS isn't appended until the body exists and could be delayed until DOM ready if your loop is broken, sometimes you may want to add CSS in your JS files for a little more fine-tuned control. Here's some code to make that easier:

var appendStyleSheet = function(id, stylesObj) {
  var css = '';

  var unwrap = function(styles) {
    $.each(styles, function(sel, rules) {
      css += sel + '{';
      $.each(rules, function(k, v) {
        if (typeof v === 'object') {
          var o = {};
          o[k] = v;
          unwrap(o);
        }
        else {
          css += k + ':' + v + ';';
        }
      });
      css += '}';
    });
  };

  unwrap(stylesObj);

  $('head').append('' + css + '');
};

appendStyleSheet('my-styles', { 
  '@media (max-width: 480px)': { 
    '.hide-on-phones': { 
      display: 'none' 
    } 
  }
});

Take a look at the original post for more information.

- Case White | Senior Front-End Engineering @ clearhead.me

Level 2

Aicke 05-29-15
 

Re: Experiment CSS - JS2CSS helper function

[ Edited ]

The link to the original post is quite helpful, because it describes why you just don't use:

$('<style type="text/css">@media (max-width: 480px) { .hide-on-phones { display: none; } }</style>').appendTo(document.head);


But you have code missing in your example here, the line

$('head').append('' + css + '');

should be(?)

$('head').append('<style id="' + id + '">' + css + '</style>');

 

Everything is hard, before it is easy.
Level 2