I'm attempting to detect a number of key combinations in javascript. I need to detect Ctrl + Left, Ctrl + Right, Right, and Left.
So far I'm just trying to detect when Ctrl is pressed. Here's what I have (JSFiddle link):
var keys = {};
$(document).keydown(function (e) {
keys[e.which] = true;
printKeys();
});
$(document).keyup(function (e) {
delete keys[e.which];
printKeys();
});
function printKeys() {
var html = '';
for (var i in keys) {
html += '<p>i: ' + i + '</p>'
if (!keys.hasOwnProperty(i)) continue;
if ($.inArray(17, keys) > -1)
html += '<p>ctrl was pressed, return val: ' + $.inArray(17, keys) + '</p>'
}
$('#out').html(html);
}
I guess I don't really understand how JQuery's inArray is supposed to work because when I press any key, it just returns -1. The if statement also evaluates to true while I only want it to do that when Ctrl is pressed. How can I fix this so that my if statement properly detects Ctrl being pressed? I'll be able to figure the rest out once I get that working properly.
EDIT: Changed if-statement to evaluate inArray returning > -1
In javascript you would need to capture the value of the window.event.ctrlKey to detect if the control key is being pressed. Here is an example of a function that would use to block pasting from the clipboard into a field using the ctrl+v keyboard shortcut:
function BlockControlV() {
var keyPressed = window.event.keyCode;
var ctrlPressed = window.event.ctrlKey;
if (ctrlPressed && keyPressed == 86) {
var ClipBoardData = window.clipboardData.getData('Text')
ClipBoardData = trim(ClipBoardData)
if (ClipBoardData != '') {
if (isNaN(ClipBoardData) == true) {
window.event.keyCode = 0;
}
}
else {
window.event.keyCode = 0;
}
}
}
Though not exactly relevant to what you're trying to do, you should be able to figure out what direction you should be heading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With