In Javascript, how do you detect if the document is in direct focus. By direct focus, I mean you're on the document, but no form elements are focused.
What I'm trying to do here is opposite of Stackoverflow's WYSIWYG editor. Stackoverflow bolds the text when you hit CTRL+B while focus is on the textarea. I want to execute a command when the user is NOT filling out any form on the page. For example, SHIFT+N goes to the next step in my application, but still allows writing capital Ns on form textareas.开发者_Python百科
I use the Prototype framework, BTW.
There is no need to track focus, it is overcomplicating things and that doesn't pass the common sense smell test... something could go wrong if you missed just one event.
If you observe the root element of a page (document
or document.body
) then all events which aren't explicitly stopped will reach there and you'll be able to filter out those that started on a form element.
document.observe('keypress', function(event, element) {
if (event.findElement('input, select, textarea') == document) {
// No input was typed on.
}
});
This example doesn't filter out anchors but could do easily by adding a
to the findElement
call.
Why don't you use a global javascript variable as a flag ?
var isFocusedOnElement = false;
And assign an onfocus trigger to all text areas,input boxes which change it to true onfocus
, and false on onBlur
.
Then you can check this flag whenever you encounter they keystrokes.
精彩评论