This question has probably been asked before, but I am not able to find a suitable search phrase to locate it, either here or on the intertubes.
I have a web page for a game which uses the keyboard, so with jQuery I have set handlers in the document:
$(document).keydown(myKeydown);
$(document).keyup(myKeyup);
$(document).blur(myBlur);
But now any text written in an input field is stolen by the document event handlers, and characters only reach the input if they are not used in the document handlers. These handlers in essence look like this:
function myKeydown(event)
{
if (event.which == 65)
{
console.log('a pressed');
return false;
}
return true;
}
Now imagine that I have a text input box; if I press any key other than ‘a’ it shows in the input, but not ‘a’ (since myKeydown is “eating” it by returning false). I could return true in any case, but then if no input box is focused I get weird things like “search when you type”, if enabled.
I have tried to add handlers for the input box:
input.keydown(function() { console.log('down'); return false; });
input.keyup(function() { console.log('up'); return false; });
input.blur(function() { console.log('blur'); return false; });
With this code I get the console.logs, but of course keys don’t reach the box (because I am doing nothing with the presses). Can I send these events somewhere so the corresponding keys appear in the input box?
Note: some people have suggested to use event.stopPropagation() instead of return false. jQuery docs say:
Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.”
That is precisely what I want: to prevent “search as you type” from kicking in, I have to prevent the default action, which is to type on an input and to “search as you type” on the page.
(Also, for some reason the keydown event handler does not have a stopPropagation() function on Firefox latest.)
Two ways to prevent this.
get the target in the event handler and ignore your code if the target is an
input/textareabind the same event to the inputs and stop propagation
the first option is the right thing to do, IMO. Try:
at the start of the event handler.