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:
function clicked () {
alert('clicked!');
//some code
}
document.onkeydown = function (e) {
var keyCode = e.keyCode;
if(keyCode == 90) {
clicked();
}
};
btnZ.onclick = clicked;
You should have a common function which executes the code, but then have two event functions.
function do() {
//some code
}
btnZ.onclick = function(e) {
do();
};
btnZ.onkeydown = function(e) {
var keyCode = e.keyCode;
if(keyCode === 90) do();
}
This will only work if the user is focused on the element.
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.
You can declare the function separately and just refer to it wherever you need it. For example,
var yourOnClickFunction = function() {
// Some code
btnZ.onclick = yourOnClickFunction;
HTML
<button id="z">Z</button>
JS
document.onkeypress = function (e) {
e = e || window.event;
var charCode = e.charCode || e.keyCode,
character = String.fromCharCode(charCode);
if (character == 'z')
alert(character);
};
document.getElementById('z').onclick = function (e){
alert(document.getElementById('z').id)
}
JSFiddle
One way is to trigger event of other element as shown in below example
<button >Hello</button>
clickButton = function(){
alert("Hello clicked")
}
document.getElementsByTagName("button")[0].onclick = clickButton
keydown = function(e){
if(e.keyCode==90)
document.getElementsByTagName("button")[0].click()
}
document.onkeydown = keydown
if using JQuery you can use trigger function. Following is sample code and also find working example in codepen.io
<button >Hello</button>
$("button").click(function(){
alert("Hello clicked")
})
$(document).keypress(function(e){
if(e.charCode == 90)
$("button").trigger("click")
})