1

Is it possible to trigger any key by javascript or jQuery ? Like when click on a button javascript will trigger F1 button or Ctrl+s button like this

<script>
function clickBtn(){
--Click the F1 button or Ctrl+s button--
}
</script>

<body>
<input type="button" onClick="clickBtn()" value="Click To Press F1 Button">
</body>
  • Isn't this essentially the same question as [Can I do SendKeys in JavaScript](https://stackoverflow.com/questions/5988230/can-i-do-sendkeys-in-javascript) – Micah Hunsberger Aug 03 '17 at 04:45

2 Answers2

1

It's possible to trigger event handlers bound to the DOM for some key press with EventTarget.dispatchEvent or jQuery's .trigger however this does not always induce the browser behavior associated with a user pressing that key. Opening the browser help or bringing up the save dialog is not possible in this way with any browser in widespread use today. This is generally a sane design decision on the part of browser vendors, it would open a lot of doors for abuse if webpages could trigger the events associated with pressing with alt-F4 or win-L on windows

Ryan Jenkins
  • 878
  • 8
  • 16
0

You can dispatch your own keyboard event like this (but you may want to include more props in the object).

window.dispatchEvent(new KeyboardEvent('keydown', {key: "F1", code: "F1"}))

Note that Internet Explorer doesn't support the KeyboardEvent constructor, so you can't use it there. Hopefully you don't need to support that :)

It's not stated in your question, but I'm guessing your goal might be to trigger app-level commands like saving and what ever F1 is bound to on your system. This method won't do that. It will only send the event to key event listeners in your js.

MDN Creating_and_triggering_events

posit labs
  • 8,951
  • 4
  • 36
  • 66