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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.