Javascript How To Use Onclick Function Also With Keyboard
I hope the title of the question fits to what I'm asking here. I have this code in HTML & javascript: var btnZ = document.getElementById(
Solution 1:
You should have a common function which executes the code, but then have two event functions.
functiondo() {
//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.
Solution 2:
Use this:
functionclicked () {
alert('clicked!');
//some code
}
document.onkeydown = function (e) {
var keyCode = e.keyCode;
if(keyCode == 90) {
clicked();
}
};
btnZ.onclick = clicked;
Solution 3:
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.
Solution 4:
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;
Solution 5:
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)
}
Post a Comment for "Javascript How To Use Onclick Function Also With Keyboard"