Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if any input has focus

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.

like image 988
Wolfr Avatar asked May 22 '13 18:05

Wolfr


People also ask

How do you know which element is focused?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

How do I test focus in HTML?

var el = document. getElementById('myElement'); el. matches(':focus'); // If it has focus, it will return true.


1 Answers

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.

like image 200
David Thomas Avatar answered Sep 23 '22 13:09

David Thomas