Search code examples
jquerykeyboard-eventskeyboard-hook

How do I replace a keystroke with jQuery?


I need to be able to replace a keystroke with jQuery. When the right arrow is pressed, I want the tab key to be pressed instead. So far I have:

<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="jquery.simulate.js"></script>
<script type="text/javascript">
    $(function () {
        $("select").each( function() {
                $(this).keydown(function(event) {
                    if (event.which == '39') {
                        $(this).simulate("keydown", { keyCode: 9, ctrlKey: false, shirtKey: false });
                        $(this).simulate("keypress", { keyCode: 9, ctrlKey: false, shirtKey: false });
                        $(this).simulate("keyup", { keyCode: 9, ctrlKey: false, shirtKey: false });
                        return false;
                    }
            });
        });
    });
</script>

39 is the right arrow, and 9 is the tab button. Also, the simulate keydown recursively calls the event handler, which is obviously bad, but even without that line, this still doesn't work.

I'm using jquery.simulate.js located at (http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/simulate/jquery.simulate.js?r=6063) because I couldn't find a way to simulate a keypress with just jQuery.

The keypress just doesn't simulate the actual key press.


Solution

  • You can't simulate actual keypresses with javascript. It's a core component of browser security. Imagine being able to simulate Alt-Tab, or Ctrl-Shift-Del.

    You can, of course, define a method that encapsulates the behavior you want to trigger, and call that method when specific keys are pressed.

    So, for example, to jump to the next select element when someone presses the right arrow while on another select element, I'd keep a list of all the select elements on the page; when the right-arrow is pressed, I'd find the position of the currently-focused select in that list, and .focus() the next one.