views:

59

answers:

3

I can't get a simple answer to this: When I press the letter J, i want it to hide $('.something') and when i press the letter H, I want it to show $('.something')

press the letter J
$('.something').hide()

press the letter H
$('.something').show()
A: 
document.addEventListener('keypress', function(e) {
    if (String.fromCharChode(e.charCode) == 'j') $('.something').hide();
    if (String.fromCharChode(e.charCode) == 'h') $('.something').show();
}, false);
Delan Azabani
inb4 Tim Down ;)
Delan Azabani
Well done Delan :) Inevitably, I have to point out to the OP and everyone else that this won't work in IE.
Tim Down
Heh, this went just as I expected :D
Delan Azabani
Given that this is a jQuery question, you could've just used `$(document).keypress()` and avoided this charade and we'd both have been happy.
Tim Down
Ah, sorry about that. I have very little jQuery experience so maybe I'm better off not answering these questions at all. However, JavaScript questions without jQuery's involvement are a rare breed these days ;)
Delan Azabani
+2  A: 
$(document).bind('keydown', function(e) {
    if (e.keyCode == 72) {
        // press the letter H
        $('.something').show()
    } else if (e.keyCode == 74) {
        //press the letter J
        $('.something').hide()
    }
    return false;
});​

crazy demo

Reigel
Missing semicolons! :O
Delan Azabani
where? hehe semicolons are optional on some situation, FYI. ^_^
Reigel
Does e.keyCode work on any browser? i.e. 'e.keyCode ? e.keyCode : e.which'
hluk
I tried, IE6,7,8,FF,GC on windows platform and works well...
Reigel
`keydown` and `keyup` cannot be used for character-based key detection. Only `keypress` contains character information.
Tim Down
@Tim - huh? your point is?
Reigel
My point is that your code may work on your keyboard but for different keyboard types or keyboards in countries other than yours, keys with `keyCode` 72 and 74 in `keydown` are not guaranteed to correspond to H and J.
Tim Down
@Tim - ahhh good point. You're the first one to tell me that. Thanks.
Reigel
A: 

Character-based key detection can only be done with the keypress event:

$(document).keypress(function(e) {
    var charCode = e.which;
    if (charCode) {
        var lowerCharStr = String.fromCharCode(charCode).toLowerCase();
        if (lowerCharStr == "h") {
            $('.something').show();
        } else if (lowerCharStr == "j") {
            $('.something').hide();
        }
    }
});
Tim Down
when adding this code to my javascript file, it caused all of my jquery/javascript to stop working... do you know why? when adding the other answers' code to my js file it also made my js/jquery stop working... hmmm.. so i can't get it to work
android.nick
There seems to have been a strange character at the end. Try it now.
Tim Down