Reputation: 35
I want to eventing more keys in my Javascript code:
<script>
function OPEN(e) {
if (e.type !== "blur") {
if (e.keyCode === 70) {
alert("Pressed F");
}
}
}
document.onkeydown = OPEN;
</script>
Upvotes: 0
Views: 71
Reputation: 14371
What I am getting from your question is that you want to detect more keys presses. The best way to detect key presses is a switch statement
function OPEN(e) {
if (e.type !== "blur") {
switch (e.keyCode) {
case 70:
alert("Pressed F");
break;
case 65:
alert("Pressed A");
break;
default:
alert("I don't know what to do with that key!");//This line is removable
break;
}
}
}
document.onkeydown = OPEN;
The way a switch
works is:
switch (VALUE) {
case THIS_VALUE:
CODE
break;
default:
CODE
break;
}
That was probably the worst explanation you've seen so you can read about here
keyCodes are kind of irritating to figure out, you can use:
function OPEN(e) {
if (e.type !== "blur") {
switch (String.fromCharCode(e.keyCode)) {
case "F":
alert("Pressed F");
break;
case "A":
alert("Pressed A");
break;
case "B":
alert("Pressed B");
default:
alert("I don't know what to do with that key!");//This line is removable
break;
}
}
}
document.onkeydown = OPEN;
When detecting key combinations, you can use &&
to make sure both key's are pressed. Without some more complicated. You can use:
e.metaKey
Window key on Windows, Command Key on Mac
e.ctrlKey
Control key
e.shiftKey
Shift key
e.altKey
Alt key
Use them as:
if (e.ctrlKey && e.keyCode === 65) {
alert("Control and A key pressed");
}
To detect all keys are currently pressed (multiple) I found this fiddle (not mine), and a question here
Upvotes: 1
Reputation: 112
may be that make what you want
<script>
function OPEN(event) {
var x = event.which || event.keyCode;
alert( "The Unicode value is: " + String.fromCharCode(x));
// The Unicode value is: a
//The Unicode value is: b
}
</script>
then add this attr to your body
<body onkeydown="OPEN(event)">
Upvotes: 1
Reputation: 424
If you're not opposed to using a library for this, I find Mousetrap.js to be awesome and very easy to use.
Here are a few examples from the link above:
<script>
// single keys
Mousetrap.bind('4', function() { console.log('4'); });
Mousetrap.bind("?", function() { console.log('show shortcuts!'); });
Mousetrap.bind('esc', function() { console.log('escape'); }, 'keyup');
// combinations
Mousetrap.bind('command+shift+k', function() { console.log('command shift k'); });
// map multiple combinations to the same callback
Mousetrap.bind(['command+k', 'ctrl+k'], function() {
console.log('command k or control k');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
// gmail style sequences
Mousetrap.bind('g i', function() { console.log('go to inbox'); });
Mousetrap.bind('* a', function() { console.log('select all'); });
// konami code!
Mousetrap.bind('up up down down left right left right b a enter', function() {
console.log('konami code');
});
</script>
Upvotes: 0