Change color of li class with javascript when keyboard key is pressed

css, html, javascript, jquery

Solution

This worked for me:

HTML

<div id="keyboard">
    <ul class="row">
        <li class="letter" id="q">Q</li>
        <li class="letter" id="w">W</li>. . .</ul>
</div>

jQuery

$(document).keypress(function(e){
    
    var which_letter = String.fromCharCode(e.which);
    $('#'+which_letter+'').addClass('red');

});

$(document).keyup(function(){
    $(".letter").removeClass('red');
});

CSS

 .red { color:#f00; }

DEMO

Note

If you would like the letter to glow no matter if he/she presses 'X' or 'x', change:

var which_letter = String.fromCharCode(e.which);

to:

var which_letter = String.fromCharCode(e.which).toLowerCase();

Otherwise the user must press exactly the value of the letter's `id`.

Problem

I've created a keyboard with HTML and CSS, and I'm trying to make the keys "glow" with a different background-color when the same key is pressed on the keyboard (the real-life keyboard that is). It looks something like this: ``` <div id="keyboard"> <ul class="row"> <li class="letter">Q</li> <li class="letter">W</li> . . . </ul> </div> ``` And i have the following javascript code: ``` $('#keyboard .letter').keydown(function() { $(this).addClass('red'); }).keyup(function() { $(this).removeClass('red'); }); ```

Original source

Related problems