Fire Keydown event in different browsers

I have been looking for an answer to this problem for a long time: to trigger the keydown event, software compatible in different browsers, such as IE, FireFox, Opera, Chrome ...

Now I found it, and I would like to share it with programmers, you can use it to fire any type of event.

<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?

+4
source share

Source: https://habr.com/ru/post/1300840/


All Articles