I hope the title of the question fits to what I'm asking here.
I have this code in HTML & javascript:
<button id="Z">Z</button>
var btnZ = document.getElementById("Z");
btnZ.onclick = function() {
// Some code
Ok, now I want to execute btnZ.onclick function when the user press "Z" on keyboard. How can I do this without duplicating the code inside btnZ.onclick function?
Use this:
If you can use HTML5, you can use the
accesskey
attribute (but it will respond to ALT + Z, and not Z only).If you can't use HTML5, you must use the
keydown
event.One way is to trigger event of other element as shown in below example
if using JQuery you can use trigger function. Following is sample code and also find working example in codepen.io
HTML
JS
JSFiddle
You should have a common function which executes the code, but then have two event functions.
This will only work if the user is focused on the element.
You can declare the function separately and just refer to it wherever you need it. For example,