Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
});
like image 930
Håvard Brynjulfsen Avatar asked Jan 31 '14 13:01

Håvard Brynjulfsen


1 Answers

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.

like image 66
display-name-is-missing Avatar answered Sep 30 '22 07:09

display-name-is-missing