Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keypress event if NOT input

I have the following jQuery events in my site

    $(window).keyup (function(event) {
        switch (event.keyCode) {
            case 68:  // Alt-N = next
                scroll ('next');
                break;
            case 65:  // Alt-P = prev
                scroll ('prev');
                break;

        }

});

});

 <script>
    $(document).keydown(function(e) {
    if(e.keyCode==68){
        window.location.href = "{PreviousPost}";
    }
    });
</script>

I'm using window and document because they both work and searching didn't result in me finding out what the difference is in terms of functionality. But anyway, what I'm wondering is how to keep the functions from firing, when it's in an input field. Cause it works and everything, but I don't want the event to fire when the user is typing only when they press the keys and are ... not typing.

It seems simple, but I really searched. Kept giving me results from other issues.

like image 447
Ming Avatar asked Dec 26 '22 23:12

Ming


1 Answers

In the event:

if ($(e.target).closest("input")[0]) {
    return;
}

What that does is see if the target originates in or passes through an input element and return without doing anything if so. More: closest | event.target Your logic for other cases would follow, e.g.:

$(document).keydown(function(e) {
    if ($(e.target).closest("input")[0]) {
        return;
    }
    if(e.keyCode==68){
        window.location.href = "{PreviousPost}";
    }
});

N.B. - If you also want to filter out select elements, then: $(e.target).closest("input, select") (and so on, for instance for button elements).

like image 170
T.J. Crowder Avatar answered Dec 28 '22 13:12

T.J. Crowder