title: Javascript: Global Element Focus Listener
body: <p>I am trying to set a listener that listens for all focus events. In particular I am trying to listen for anytime an input or textbox gains focus. Per some research, the widely accepted way to achieve this is like this:</p>
  
  <pre><code>document.body.onfocus = function(event) {
     //Check the event.target for input/textbox
     //Do something
  };
  </code></pre>
  
  <p>But the document.body.onfocus doesn't seem to fire, ever. I thought it might be because the document doesn't actually ever receive focus so I tried:</p>
  
  <pre><code>document.body.focus();
  </code></pre>
  
  <p>To initially "set" the focus, but this doesn't work either.</p>
  
  <p>Any ideas on how I can listen to a focus event on all inputs/textboxes without actually setting the event directly on the element itself? Vanilla javascript only please, I am not using a framework.</p>
  
  <p>Per the accepted answer here is some working code:</p>
  
  <pre><code>var focusHandler = function(event) {
      var type = event.target.nodeName.toLowerCase();
      if(type == 'input' || type == 'textarea') {
          //Do something
      }
  };
  document.body.addEventListener('focus', focusHandler, true); //Non-IE   
  document.body.onfocusin = focusHandler; //IE
  </code></pre>