5

This is my code:

<script>
function f(){
var i=document.getElementById("i");
i.focus();
 var evt = document.createEvent("KeyboardEvent");
    evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 

0, 32);
    i.dispatchEvent(evt);
}
</script>
<body onload="f();">
<input id="i"/>
</body>

Open the script in firefox and it's working. The empty space within the input box shows that the code has worked.

However the above piece of code doesn't work in Chrome, Safari, Opera etc etc.

How do we modify the code above to make it work in these browsers?

Pacerier
  • 86,231
  • 106
  • 366
  • 634
  • [Reproduced in Opera 11 with JS Fiddle](http://jsfiddle.net/davidThomas/PsZbj/1/), but Chromium 12 reports: `Uncaught Error: NOT_SUPPORTED_ERR: DOM Exception 9`, and Firefox 4: `Error: uncaught exception: [Exception... "Operation is not supported" code: "9" nsresult: "0x80530009 (NS_ERROR_DOM_NOT_SUPPORTED_ERR)" location: "http://fiddle.jshell.net/_display/ Line: 19"]`. I suspect that this is ***not*** an Opera-specific issue, unless the repro demo was hideously wrong. – David Thomas Jun 20 '11 at 04:27
  • You need to show more context of your code. Can you please a minimum viable example of what the problem is? Three lines of code is not enough to adequately diagnose the issue. – Nathan Bell Jun 20 '11 at 04:29
  • @David i scoped the code from http://stackoverflow.com/questions/668720/how-do-i-shift-the-visible-text-in-a-narrow-input-element-to-see-the-cursor-at-th/668856#668856 – Pacerier Jun 20 '11 at 04:56
  • 1
    Thanks Jack, but that's still not enough context to help. That is just a function. We need to see where you are executing it (how you are calling it and what your HTML is). Please link to a small example of you calling that function in a way that triggers your error. – Nathan Bell Jun 20 '11 at 05:05

2 Answers2

6

For Webkit-based browsers (Safari/Chrome), the event initialization call should look a bit differently (see https://bugs.webkit.org/show_bug.cgi?id=13368):

initKeyboardEvent(in DOMString typeArg, 
                  in boolean canBubbleArg, 
                  in boolean cancelableArg, 
                  in views::AbstractView viewArg, 
                  in DOMString keyIdentifierArg, 
                  in unsigned long keyLocationArg, 
                  in boolean ctrlKeyArg, 
                  in boolean shiftKeyArg, 
                  in boolean altKeyArg, 
                  in boolean metaKeyArg, 
                  in boolean altGraphKeyArg);
Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
4

To add to Alexander's response:

There is a webkit bug that keyboard events initialized using initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735

A working solution for this is posted in this SO answer.

Community
  • 1
  • 1
tanushree
  • 763
  • 1
  • 7
  • 20