JQuery: press J and do something, press H and do something else

I cannot get a simple answer to this question: 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()
+3
source share
3 answers
$(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 demonstration

+5
source
document.addEventListener('keypress', function(e) {
    if (String.fromCharChode(e.charCode) == 'j') $('.something').hide();
    if (String.fromCharChode(e.charCode) == 'h') $('.something').show();
}, false);
0
source

Character-based key detection can only be performed with an event keypress:

$(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();
        }
    }
});
0
source

Source: https://habr.com/ru/post/1766158/


All Articles