I am building something with keyboard shortcuts e.g. you press Ctrl+m to open a menu. I use jQuery and the jwerty plugin for that, this looks like the following code:
jwerty.key('m', function () {
toggleMenu();
});
Tapping the "m" key triggers the toggleMenu function.
Now I was wondering how to prevent this function from being triggered while a user is typing in an input field or textarea.
Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
var el = document. getElementById('myElement'); el. matches(':focus'); // If it has focus, it will return true.
I've never used jwerty, but I'd suggest:
jwerty.key('m', function (e) {
if (e.target.tagName.toLowerCase() !== 'input') {
toggleMenu();
}
});
This tests the target of the event, and, if it's not an input
, calls the toggleMenu()
function; if it is an input
, it does nothing (though you could explicitly return false
if you'd prefer).
To account for textarea
, as I really should have done, the above could be extended (to add another clause to the if
assessment, or the following, switch
-based approach could be taken:
jwerty.key('m', function (e) {
switch (e.target.tagName.toLowerCase()) {
case 'input':
case 'textarea':
break;
default:
toggleMenu();
break;
}
});
If the target-element is either an input
or textarea
, pressing m
does nothing, whereas if not either of those two elements the default state is entered and toggleMenu()
is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With