Javascript event redirection

Is there an easy way to "forward" an event in Javascript? My ultimate goal here is to increase the responsiveness of the user interface as follows: I have a website with one text input field that sends a request to the underlying database. If the user presses a key when the input field is not in focus, I would like to capture the key press event at the document level and forward it to the input field. (This seems like a fairly common way to increase user interface sensitivity, for example, Google does this with its main search site.)

So, I have a text input field like this:

<input id="query" onkeydown="f(event)">

And I'm trying to forward the event as follows:

function handler(ev)
{
    var query = document.getElementById("query");
    query.dispatchEvent(ev);
}

document.addEventListener("keydown", handler, false);

, - addEventListener dispatchEvent, Firefox, . Javascript: Error: uncaught exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIDOMEventTarget.dispatchEvent]"

, ? initKeyEvent, ?

+3
3

:

HTML (index.html):

<!DOCTYPE html>
<html>
    <head>
        <title>Stackoverflow</title>
        <script type="text/javascript" src="sof.js"> </script>
    </head>
    <body>
        <input id="query" onkeydown="f(event);"/>
    </body>
</html>

Javascript (sof.js):

function simulateKeyDown () {
    // DOM Level 3 events
    var evt = document.createEvent ("KeyboardEvent");
    // DOM Level 3 events
    evt.initKeyboardEvent ("keydown", false, false, null, false, false, false, false, 0, 0);
    var query = document.getElementById ('query');
    query.dispatchEvent (evt);
}

window.onload = function () {
    document.addEventListener ('keydown', simulateKeyDown, false);
}

function f (ev) {
    console.log ('ciao');
}

, keydown . , KeyboardEvent, ( "keydown" ), . , , ;)

:

+2

, , . , -

document.addEventListener("keydown", function(e) {
    if (e.target.oMatchesSelector("form *, fieldset *, input, textarea"))
        return; // Opera-specific, but I think you get the point of MatchesSelector
    if (e.metaKey || e.ctrlKey)
        return;
    if (e.keyCode < 46 || e.keyCode > 90)
        return;
    document.getElementById("query").focus();
}, false);

keydown chararcter, - .

+1

@Bergi, , , - focus - , , ! :

document.addEventListener('keydown', function(evt) {
    document.getElementById('query').focus();
}, false);

keydown query.

0

All Articles