Home > Net >  Using up/down keys to select list item JS/jQuery
Using up/down keys to select list item JS/jQuery

Time:06-01

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 >
      <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/

CodePudding user response:

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();

  }
});

CodePudding user response:

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();

  }
});
  • Related