views:

218

answers:

0

I was looking long time to get answer to this task: fire a keydown event programmatically compatible under different browsers like IE, FireFox, Opera, Chrome...

now I found it and i would like to share it with programmers, You may use it to fire event of any type.

<html>
<body>
<script language="JavaScript">
function first() {
    var el=document.getElementById("button");
    fire(el,'keydown');
} 

function fire(el,evttype) {
   if (document.createEvent) {
     var evt = document.createEvent('HTMLEvents');
     evt.initEvent( evttype, false, false);
     el.dispatchEvent(evt);
   } else if (document.createEventObject) {
     el.fireEvent('on' + evttype);
   }
}
</script>

<div style="background: #cf2255; width:'100%';" align="center">
<font color="#ffffcc" size="12pt"><b>KeyDown event</b></font></div>
<p> &nbsp; </p>
<center>
<button onclick="alert('onclick event button 1'); first();">
 1 Generate Event</button>
<button id="button" onclick="alert('onclick event button 2');"
 onkeydown="alert('keydown event button 2!');">2 Direct Event</button>
</center>
</body>
</html>

Any comments?