Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fake keypress

Status
Not open for further replies.

jaschulz

Programmer
May 20, 2005
89
FR
The function below is intended to put an upper-case "P" into a textarea. It raises no exception or error, but it doesn't actually do anything except move the focus to the textarea in question.

What am I doing wrong?

JAS

function fakeKeyPress(elementID){
var thisTarget = document.getElementById(elementID);
thisTarget.focus();
if( window.KeyEvent ) {
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent( 'keyup', true, true, window, false, false, false, false, 0x50, 0 );
} else {
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent( 'keyup', true, true, window, 1 );
evObj.keyCode = 0x50;
}
thisTarget.dispatchEvent(evObj);
}
 
What browser is it not working in?

howtocreate.co.uk said:
This is currently supported by Opera 7+, Mozilla/Firefox, Konqueror 3.0+, and Safari. It is also partially supported by iCab 3+, ICEBrowser 5+, and NetFront 3.3+.

Hope this helps,
Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
I've tried IE6, FF 1.5.0.1 and Opera 8.54 and I can't get it to work in any of them.

Try the below in any of them, you'll see what I mean.

JAS

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"
<html>
<head>
<title>Test</title>
<script type="text/javascript">

function fakeKeyPress(elementID){
var thisTarget = document.getElementById(elementID);
thisTarget.focus();
if( window.KeyEvent ) {
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent( 'keyup', true, true, window, false, false, false, false, 0x50, 0 );
} else {
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent( 'keyup', true, true, window, 1 );
evObj.keyCode = 0x50;
}
thisTarget.dispatchEvent(evObj);
}
</script>
</head>
<body>
<textarea rows=2 cols=20 id="ta"></textarea>
<br>
<br>
<input type="button" value="fake P" onclick="fakeKeyPress('ta');" />
</body>
<html>
 
Some progress. A slight change (see below) to the initKeyEvent call has it working in FF. No luck yet with IE or Opera.

JAS

function fakeKeyPress(elementID, thisKeyCode){
var thisTarget = document.getElementById(elementID);
thisTarget.focus();
if( window.KeyEvent ) {
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent( 'keypress', true, true, window, false, false, true, false, 0, thisKeyCode );
} else {
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent( 'keypress', true, true, window, 1 );
evObj.keyCode = 0x50;
}
thisTarget.dispatchEvent(evObj);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top