faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

105 of 127 people (83%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Is it possible to generate a keypress event in a JS and fire it to write in an input-field?
I want to script a fireEvent that will do the same thing as pressing Alt-Tab. How?
Is it possible to simulate a KeyPress event?

Jul 9th, 2002 21:50
Joel Newton, Chris Hightower, Juergen Thelen, Samsamoddin Rajaei,


Chris, I too am in search of a means to simulate a keypress event, and 
I do not think the fireEvents() method will serve our purposes. 
The code below - and as far as I can tell, all possible uses of 
fireEvents() - don't actually simulate an event. Instead, they simply 
replace/shortcut the occurance of the event and kick off the specified 
event handler. 
However, I haven't given up the belief that a keypress can somehow be 
simulated, and will post any nuggets that msdn happens to reveal.
regards,
Joel
---
Actually, it is possible to fireEvents and even keystrokes (at least in 
IE), though it won't generate events external to the document.  Here's 
a simple script...
function sendCtrlF() {
  var evtObj = document.createEventObject();
  var str = 'F';
  evtObj.ctrlKey = true;
  evtObj.keyCode = str.charCodeAt(0);
  document.fireEvent("onkeydown",evtObj);
  event.cancelBubble = true;
}
As you can see here I was trying to generate a Ctrl-F to open the 
browser's Find dialog box, but no such luck.  You may be able to cause 
such havoc using Netscape, but I haven't tested with it.
I know this works because I tested it with a simple keypress event 
handler that displayed caught and displayed any keystrokes. For 
example...
document.onkeydown=hotkeyHandler;
function hotkeyHandler() {  
  alert(event.keyCode);
}
Chris
> Although it is possible to capture keystrokes with JavaScript, it is 
> NOT possible to emulate/simulate/mimic keystrokes or generate 
> appropriate events with JavaScript.
> Allowing the emulation of keystrokes through JavaScript would rise a 
> heavy security risk for the user, so I don't think any browser vendor 
> will ever implement it.
> Juergen