Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
Using up/down keys to select list item JS/jQuery

I have a list of items that get populated dynamically based on search terms. I want the list items to be selectable/focused when using the up/down keys and ESC to hide the dropdown.

<form>
  <div>
    <div class="field">
      <input type="text" id="dropdown_input" name="query">
    </div>
    
    <!-- dropdown_results inserted into DOM dynamically from search query -->
    <div id="dropdown_results">
      <ul id="dropdown_results_ul">
        <li>
          <a href="/example1">example1</a>
        </li>
        <li>
          <a href="/example2">example2</a>
        </li>
        <li>
          <a href="/example3">example3</a>
        </li>
      </ul>
    </div>
  </div>
</form>

<script>
    if (e.keyCode == 40) {
      jQuery("a:focus").parent().next().find("a").focus();
    }
    if (e.keyCode == 38) {
      jQuery("a:focus").parent().prev().find("a").focus();
    
    }
</script>

I would ideally like to do this using Bootstrap5, as that has native up/down/ESC support for button dropdowns, but I cant work out how to use that with li items when the parent ul is inserted into the DOM.

JSFiddle Example: https://jsfiddle.net/eupy9Lsc/1/

JSFiddle Bootstrap Example: https://jsfiddle.net/jr52tomd/

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your javascript isn't listening to any key events. You can resolve this with something like...

jQuery(document).on('keydown', function(e) {
  if (e.keyCode == 40) {
    jQuery("a:focus").parent().next().find("a").focus();
  }
  if (e.keyCode == 38) {
    jQuery("a:focus").parent().prev().find("a").focus();

  }
});
about 4 years ago · Juan Pablo Isaza Report

0

fixed this using 2 listeners:

jQuery("#dropdown_input").on('keydown', function(e) {
  if (e.keyCode == 40) {
    jQuery("#dropdown_results").find('a:first').focus();
  }
});


jQuery("#dropdown_results").on('keydown', function(e) {
  if (e.keyCode == 40) {
    jQuery("a:focus").parent().next().find("a").focus();
  }
  if (e.keyCode == 38) {
    jQuery("a:focus").parent().prev().find("a").focus();

  }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!