5

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');
});
Håvard Brynjulfsen
  • 819
  • 1
  • 12
  • 22

2 Answers2

8

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.

Community
  • 1
  • 1
display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
0

As i can see you are using jQuery. So it is easy to trigger key events like this one for example:

var e = jQuery.Event("keydown");
e.which = 50; // Your code value here
$("input").trigger(e);

Additionally, if you want to use clicks on your keyboard then you must use input type of field.