title: Appending CSS to a randomly generated class name via JS -- is a callback needed?
body: <p>I am working on browser extension, and part of the functionality needs to add random class names to elements that I am targeting, and apply CSS to those elements.. particularly the CSS pseudo-selector ":focus" .</p>
  
  <p>I have a couple of functions that work together properly, but if you run the script a few times, the function that applies the CSS fails, because it requires data from the first function that hasn't finished yet. I've been reading about callbacks and it seems like it could possibly be used here to make it work properly, but I really can't wrap my head around how to make it work.</p>
  
  <p>This is the code: (refresh the output again and again, it breaks ~ 1:10 times)</p>
  
  <p><strong>JSBin</strong>: <a href="http://jsbin.com/jibas/1/edit" rel="nofollow">http://jsbin.com/jibas/1/edit</a></p>
  
  <pre><code>// random string generator
  function uniqueClassName(L){
      var s= '';
      var randomchar=function(){
          var n= Math.floor(Math.random()*62);
          if(n&lt;10) return n; //1-10
          if(n&lt;36) return String.fromCharCode(n+55); //A-Z
          return String.fromCharCode(n+61); //a-z
      };
      while(s.length&lt; L) s+= randomchar();
      return s;
  }
  
  // generate a random class name
  var thisBoxNewClass = uniqueClassName(24);
  
  // append the random class name to the 'a' tag;
  document.getElementById('hi').className += thisBoxNewClass;
  
  // apply a ':focus' css style to the newly generated class name
  function appendStyle(styles) {
    var css = document.createElement('style');
    css.type = 'text/css';
    css.appendChild(document.createTextNode(styles));
    document.getElementsByTagName("head")[0].appendChild(css);
  }
  
  // the style that is going to be targeted to the class with the random name
  // (it doesnt always work)
  // and a global style that doesnt rely on the random string generator
  // (always works)
  var styles = 'a.' + thisBoxNewClass + ' { color: #0f0 !important }';
  styles += 'body { color: red !important}';
  
  // run it
  window.onload = function() { appendStyle(styles); };
  </code></pre>
  
  <p>If you run this script several times, notice the 'hello' text doesn't always turn green. I thought perhaps I could set up a condition to wait until thisBoxNewClass equaled something other than undefined, then run the appendStyle function, but that also didn't work. It almost seems like a browser bug, but its weird because it happens in every browser I've tried. Not really sure what the deal is. Any solutions would be greatly appreciated.</p>