kst
kst

Reputation: 1518

jquery element select on keyboard keypress code

I have a ul list and I want to change the background color of li when I press a key on keyboard. Example. I press a on keyboard and change the background of li which text was a.

<ul>
    <li>a</li>
    <li>b</li>
    <li>2</li>
</ul>

Which is the best and simple way to get this?

Upvotes: 2

Views: 1998

Answers (3)

alex
alex

Reputation: 490303

You could do something like this...

var li = $("ul li");

$(document).keypress(function(event) {
     li
      .filter(function() { 
         return $(this).text() == String.fromCharCode(event.which).toLowerCase();
      })
      .css("background-color", "#f00");
});

Upvotes: 4

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382170

I would first build a map of li so they're easily found and so that the heavy computation of the texts doesn't have to be done at each key press, then just test the key on keypress :

var map = {};
$('li').each(function(){
   var key = $(this).text().trim();
   if (key.length==1) map[key]=$(this);
});
console.log(map);
$(window).keypress(function(e){
  var key = String.fromCharCode(e.which);
  if (map[key]) map[key].css('background-color','red');
});

Demonstration

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

You can pass event as argument inside keypress and then using event.which you can then track which key is pressed after that check if li contains that word using jQuery:contain();

Example

$(document).keypress(function(e){
   var keypressed = e.which;

   //process for checking pressed key value 
   $('ul li:contains('+ returned value of above process +')').css(
   {
      'background-color':'red'
   });
});

Upvotes: 1

Related Questions