0

I have unordered list with single character in every li. If a user pressed any letter on the keyboard I wanted to add css class to the corresponding li on my page . If the user pressed A on the keyboard, I want to find the li that has A as its content and add css class to it

    <div>
      <ul class ='list'>
       <li>a</li>
       <li>b</li>
       <li>c</li>
       ...
       <li>z</li>
      </ul>
    </div>

This is how i started it

      $(document).keypress(function(e){
      var x = e.which;
      if((x >= 65 && x <= 90)||(x >=97 && x <= 122)||(x >=48 && x <= 57)) {
         checkfirst(x);

       }
      });
     // pick list item with the text content of the value passed
     function checkfirst(x){
       var y = $('.list').find('li');
       // code will go here
       //am trying to find the li with text equal to the argument passed
     }
tsinat
  • 235
  • 1
  • 3
  • 16
  • Please add your HTML to the question, along with the JS code you've written to attempt to achieve this yourself. At the moment your question is very 'write my code for me' and is likely to be closed. – Rory McCrossan Apr 02 '16 at 20:33

1 Answers1

2

Do not use keypress, instead use keyup. For details read this post Key event differences.

I created a function to add a class active when the character pressed on the document correspond to the content of the menu line.

$(document).on('keyup', function(e) {
  if (e.shiftKey == false && e.ctrlKey == false) {
    // get the character typed
    var charTyped = String.fromCharCode(e.which);

    // remove style active from all li with no child and add this to the elements with the
    // content matching the character typed
    $('div ul.list li:not(:has(*))').removeClass('active').filter(function() {
      return this.textContent.toUpperCase() == charTyped;
    }).addClass('active');
  }
});
.list {
  font-family: Verdana, sans-serif;
  font-size: 12px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.list li {
  background: yellowgreen;
  display: block;
  width: 150px;
  height: 30px;
  margin: 2px 0;
  font-size: large;
}
.active {
  background-color: #54BAE2 !important;
}
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<div>
    <ul class ='list'>
        <li>a</li>
        <li>b</li>
        <li>c</li>
        ...
        <li>z</li>
    </ul>
</div>
Community
  • 1
  • 1
gaetanoM
  • 41,594
  • 6
  • 42
  • 61