MeTe-30
MeTe-30

Reputation: 2542

JS > Prevent custom defined keyboard shortcuts while typing

I want to define <Shift> + ? shortcut to open specific help modal in each page (I mean each page has different content). Just like Gmail.
There are hundreds of ways to implement that, but my question is how to prevent opening modal (triggering event) while user is typing in input or ... !
The project is so big and i cannot go back and write event for all inputs, textareas or ... to prevent my shortcut on focusing them and reactivate it on element blur.
So i need dynamic idea! No matter its Javascript, jQuery or Angular!
For downvoter guys that want to see dummy duplicate codes:

$document.bind("keypress", function(e) {
    if (e.shiftKey && e.keyCode == 191) {...}
});

Upvotes: 2

Views: 321

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073988

Check for whether the event originated in an input or textarea:

$document.bind("keypress", function(e) {
    if (e.shiftKey && e.keyCode == 191 &&
        !$(e.target).closest("input, textarea").length // <=== The check
        ) {
       // It did
    if (e.shiftKey && e.keyCode == 191) {...}
});

I've used closest there out of habit for doing this in the general case, but in this specific case it's a bit silly: You just need is or check e.target.tagName.toUpper() against "INPUT" and "TEXTAREA", neitherinputnortextarea` can have descendant elements:

$document.bind("keypress", function(e) {
    if (e.shiftKey && e.keyCode == 191 &&
        !$(e.target).is("input, textarea") // <=== The check
        ) {
       // It did
    if (e.shiftKey && e.keyCode == 191) {...}
});

Upvotes: 2

Related Questions