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');
});
7
  • So what's the problem? Commented Jan 31, 2014 at 14:01
  • The color doesn't change when I press a key Commented Jan 31, 2014 at 14:02
  • 1
    How can you press a key there? It's not an input field? Commented Jan 31, 2014 at 14:02
  • I'm just trying to make the keys "glow" when pressing them on my keyboard, without an input field.. Is it possible? Commented Jan 31, 2014 at 14:03
  • 1
    Do you mean that if the user presses a certain character, that character should glow? Commented Jan 31, 2014 at 14:04

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.