title: How to navigate through elements with arrow keys
body: <p>I have the following list of images:</p>
  <pre><code>&lt;figure&gt;
    &lt;span&gt;
      &lt;img src=&quot;images/img_01.jpg&quot;&gt;
    &lt;/span&gt;
  &lt;/figure&gt;
  
  &lt;figure&gt;
    &lt;span&gt;
      &lt;img src=&quot;images/img_02.jpg&quot;&gt;
    &lt;/span&gt;
  &lt;/figure&gt;
  
  &lt;figure&gt;
    &lt;span&gt;
      &lt;img src=&quot;images/img_03.jpg&quot;&gt;
    &lt;/span&gt;
  &lt;/figure&gt;
  </code></pre>
  <p>Clicking on a <code>&lt;figure&gt;</code> element assigns class 'open' to it.</p>
  <p>The behaviour I wish to achieve:</p>
  <ol>
  <li><p>Press left-arrow-key: <code>.removeClass('open');</code> from current figure and <code>.addClass('open');</code> to previous figure (or the last figure in line when the current figure is the first one).</p>
  </li>
  <li><p>Press right-arrow-key: (<code>.removeClass('open');</code> from current figure and <code>.addClass('open');</code> to next figure (or the first figure in line when the current figure is the last one).</p>
  </li>
  <li><p>When there is no figure element with class '.open' assign this class to the first figure element in line.</p>
  </li>
  </ol>
  <p>I am quite new to jQuery, and believe I have to first make an array of the figure elements. Then detect if an arrow button has been pressed.</p>
  <p>What I have tried:</p>
  <pre><code>$currentImage = $('.open');
  
  $('body').on(&quot;keyup&quot;, function(e) {              
      var code = e.which;
  
      if (code == 37) { e.preventDefault();
        $currentImage = $currentImage.prev();
      }
  
      else if (code == 39) {
          e.preventDefault();
        $currentImage = $currentImage.next();
      };
  });
  </code></pre>
  <p>I'm having trouble understanding how to make this work, and could not find another Stackoverflow question similar to mine. Any help or pointing in the right direction would be very much appreciated!</p>