title: Javascript - Focus element on keydown, when no element in the page has focus
body: <p>I have a set of buttons. When they have focus, they change color.
  They can get focus when the user hovers over them or when the user uses the up and down arrow keys.</p>
  
  <p>When no button has focus (when the user clicks somewhere else, for example), pressing the arrow keys will shift the focus to the first button. At least, that's what is intended.</p>
  
  <p>However, since I have the same keys performing different things, whenever I press the down key the focus goes to the first button, and immediately to the second one.</p>
  
  <p>I cannot seem to find a way to make this work as I would like it to. Is there anything I can do at all to keep the focus on the first button when the down arrow key is pressed, when no button has focus?</p>
  
  <p>This is what I am working with:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var divs = document.getElementsByClassName("blueBtn");
  for (var i = 0; i &lt; divs.length; i++) {
      divs[i].addEventListener("keyup", function(event) {
          if (event.keyCode == 38) {
              if (this.previousElementSibling) {
                  this.previousElementSibling.focus();
              }
          } else if (event.keyCode == 40) {
              if (this.nextElementSibling) {
                  this.nextElementSibling.focus();
              }
          }
      }, false);
      divs[i].addEventListener("mouseover", function(event) {
          this.focus();
      }, false);
  }
  
  document.body.addEventListener("keydown", function(event) {
      if (document.body === document.activeElement &amp;&amp; (event.keyCode === 38 || event.keyCode === 40)) {
          defaultBtn.focus();
      }
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.blueBtn {
      display: block;
  }
  
  .blueBtn:hover,
  .blueBtn:focus {
      background-color: blue;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button id="defaultBtn" class="blueBtn" autofocus&gt;Button 01&lt;/button&gt;
  &lt;button class="blueBtn"&gt;Button 02&lt;/button&gt;
  &lt;button class="blueBtn"&gt;Button 03&lt;/button&gt;
  &lt;button class="blueBtn"&gt;Button 04&lt;/button&gt;</code></pre>
  </div>
  </div>
  </p>