Here is how I was able to capture CTRL+C in jQuery
$(window).bind('keydown', function (event) {
if (event.ctrlKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 'p':
event.preventDefault();
printFunc();
break;
}
}
});
How can i do the same for ALT+F+P
$(window).bind('keydown', function (event) {
if (event.altKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 'f':
event.preventDefault();
//************ Need help for identifying p **************
// alert('Alt-f');
printFunc();
break;
}
}
});
I tried this also but no luck:
if (event.altKey && event.which == 70 && event.which == 80) {
alert('Alt-f-p');
}
This works, but only if you do "p" before "f". In Chrome at least, Alt+F activates a browser function. Live demo (click).
var pressed = {};
$(document).keydown(function(event) {
//event.altKey 70 80
var k = event.keyCode;
if (event.altKey && (k == 70 || k == 80)) {
pressed[k] = true;
console.log(k);
}
if (pressed[70] && pressed[80]) {
console.log('all pressed!');
}
});
$(document).keyup(function() {
pressed = {};
});
Perhaps you would want to adapt it to use something not conflicted?
Related
I'm writing code to execute a specific function when the ctrl + shift + z key is pressed. When I press two keys at the same time, it works fine, but when I press three keys, the event does not occur. Below is the code I wrote.
try1:
document.onkeydown = function (e) {
if (e.ctrlKey && e.key === 'z') { // It works
undo() // ctrl+ z
}
else if (e.ctrlKey && e.shiftKey && e.key==='z' ) { //It doesn't work
redo(); //ctrl + shift + z
}
}
try2:
document.onkeydown = function (e) { //
var ctrl, shift,z
console.log(e.key)
switch (e.key) {
case 'Control':
ctrl = true;
break;
case 'Shift':
shift = true;
break;
case 'Z':
z = true;
break;
}
if (ctrl&&shift&&z) redo()
}
Neither of these will work if you're typing on three keyboards.
How to make it work when ctrl+shift+z is pressed
Change the order of the conditions, as the first condition is always true if the second is true, causing the code for the second condition to never execute.
document.onkeydown = function(e) {
if (e.ctrlKey && e.shiftKey && e.key === 'Z') {
undo()
} else if (e.ctrlKey && e.key === 'Z') {
redo();
}
}
I nice way to keep track of pressed keys is with an object:
const keys = {}
function onKeyDown(e) {
keys[e.key.toLowerCase()] = true
doSomething()
}
function onKeyUp(e) {
keys[e.key.toLowerCase()] = false
}
window.addEventListener('keydown', onKeyDown)
window.addEventListener('keyup', onKeyUp)
function doSomething() {
console.log(keys)
if (keys.control && keys.shift && keys.z) {
console.log("redo!")
} else if (keys.control && keys.z) {
console.log("undo!")
}
}
Since I'm using canvas to render typed text and need to use other key events like backspace, forward delete, tab and arrow keys, I need compatibility between browsers and using the keypress and keydown events. When attempting to use the paste event, the keydown event takes priority and cancels the paste event from ever happening.
A related question, but does not solve my issue since I want to keep both the keydown and keypress events
keypress and keydown take priority over paste event in Firefox & Safari
My event listeners:
window.addEventListener('paste', pasteText);
window.addEventListener("keypress", keyPressHandler, true);
window.addEventListener("keydown", keyDownHandler, true);
function pasteText (event) {
console.log('paste');
if(selectedLine !== ''){
var clipboardData, pastedData;
event.stopPropagation();
event.preventDefault();
clipboardData = event.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
}
}
function keyPressHandler(event){
if(selectedLine != '' &&
$(".sp-input").is(":focus") === false &&
$("input").is(":focus") === false){
var key = event.keyCode;
if (key == 13){ // Enter key
gotoNextLineOrDeselect();
}else if (key == 115 && (event.ctrlKey||event.metaKey)|| (key == 19)) {
// this will be for modifier keys like ctrl, option and command
event.preventDefault();
// do stuff
}else if(key !== 8 &&
key !== 9 &&
key !== 37 &&
key !== 38 &&
key !== 39 &&
key !== 40 &&
key !== 46){
key = event.charCode;
addletter(String.fromCharCode(key));
event.preventDefault();
}
}
}
function keyDownHandler(event){
if(selectedLine != '' &&
$(".sp-input").is(":focus") === false){
var key = event.keyCode;
switch(key){
case 8:
backspace();
break;
case 9: // tab
var nextLine;
if(selectedLine === 'line1' && lineBlankOrWhitespace('line2') === false){
nextLine = 'line2';
}else if(selectedLine === 'line2' && lineBlankOrWhitespace('line3') === false){
nextLine = 'line3';
}else if(selectedLine === 'line2' & lineBlankOrWhitespace('line3') ||
selectedLine === 'line3'){
nextLine = 'line1';
}else return;
selectLine(nextLine, false);
textInsertIndex = textLines[selectedLine].keyHistory.length;
setCaretXPosWithTextInsertIndex(selectedLine, 0);
renderScreen();
event.preventDefault();
break;
case 37: // left arrow
arrowOver(-1);
event.preventDefault();
break;
case 39: // right arrow
arrowOver(1);
event.preventDefault();
break;
case 38: // up arrow
var prevLine = selectedLine === 'line3' ? 'line2' : 'line1';
if(selectedLine !== 'line1'){
selectLine(prevLine, false);
textInsertIndex = textLines[selectedLine].keyHistory.length;
}else{
textInsertIndex = 0;
}
setCaretXPosWithTextInsertIndex(selectedLine, 0);
renderScreen();
event.preventDefault();
break;
case 40: // down arrow
var nextLine = selectedLine === 'line1' ? 'line2' : 'line3';
if(lineBlankOrWhitespace(nextLine) === false &&
selectedLine !== 'line3'){
selectLine(nextLine, false);
}
textInsertIndex = textLines[selectedLine].keyHistory.length;
setCaretXPosWithTextInsertIndex(selectedLine, 0);
renderScreen();
event.preventDefault();
break;
case 46: // forward delete key
forwardDelete();
break;
}
}
}
When pasting, is there a way to prevent the keypress and keydown events from being triggered?
Here's the answer: I need to preventDefault if it exists. Then I need to check for the modifier keys on the other key events and return false if they are pressed.
function pasteText (event) {
if (event.preventDefault())
event.preventDefault();
console.log('paste');
}
function keyPressHandler(event){
if (event.ctrlKey||event.metaKey) {
return false;
}
}
function keyDownHandler(event){
if (event.ctrlKey||event.metaKey) {
return false;
}
}
I want to write it in a better, optimized way. I thought maybe I should use jquery each function but not sure how to write it. Basically there are list of 7 buttons and both NUM keys and regular number keys are attached to related buttons.
the HTML is here http://jsfiddle.net/wAwed/1/
$(document).keydown(function (e) {
if ($(e.target).is('input') || $(".answerbtns").length != 0 ) { return }
/* keyboard 1 */
else if (e.keyCode == 97 || e.keyCode == 49 ) {
$("#.ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl00_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 2 */
if (e.keyCode == 98 || e.keyCode == 50 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl01_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 3 */
if (e.keyCode == 99 || e.keyCode == 51 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl02_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 4 */
if (e.keyCode == 100 || e.keyCode == 52 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl03_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 5 */
if (e.keyCode == 101 || e.keyCode == 53 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl04_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 6 */
if (e.keyCode == 102 || e.keyCode == 54 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl05_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
/* keyboard 7 */
if (e.keyCode == 103 || e.keyCode == 55 ) {
$("#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl06_lbAnswers")[0].click();
e.stopPropagation();
return false;
}
});
sure, create a map of keycodes that link keycodes to the target element, then use a loop. Or use object key/value pairs. Here's a sample for two of them:
var keys = {
97: "#.ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl00_lbAnswers",
49: "#.ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl00_lbAnswers"
}
$(document).keydown(function (e) {
if ($(e.target).is('input') || $(".answerbtns").length != 0 ) { return }
/* keyboard 1 */
if (keys[e.keyCode]) {
$(keys[e.keyCode])[0].click();
e.stopPropagation();
return false;
}
});
And, if they all have the class "answerbtns", you can do this:
var numeric = [97,98,99,100,101,102,103];
var numpad = [49,50,51,52,53,54,55];
$(document).keydown(function (e) {
if ($(e.target).is('input') || $(".answerbtns").length == 0 ) { return }
/* keyboard 1 */
var index = $.inArray(e.which,numeric);
if ( index == -1 ) {
index = $.inArray(e.which,numpad);
}
if ( index != -1 ) {
$(".answerbtns")[index].click();
e.stopPropagation();
return false;
}
});
http://jsfiddle.net/wAwed/2/
This option reduces some code.
var custKeyCode = [97, 49, 98, 50];
if (e.keyCode == 97 || e.keyCode == 49 ) {
myid = "#.ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl00_lbAnswers";
}
if (e.keyCode == 98 || e.keyCode == 50 ) {
myid = "#ctl00_ContentPlaceHolder1_rptrQuizQuestions_ctl01_lbAnswers";
}
......
......
for(var i=0; i<custKeyCode.length; i++){
if(custKeyCode[i] == e.keyCode){
$(myid)[0].click();
e.stopPropagation();
return false;
}
}
I have a function which detect max length. but the problem is that when the max length reached Ctrl+A combination does't work. How can I detect Ctrl+A combination through javascript.
This is my maxlength code.
if (event.keyCode==8 || event.keyCode==9 || event.keyCode==37 || event.keyCode==39 ){
return true;
} else {
if((t.length)>=50) {
return false;
}
}
Check event.ctrlKey:
function keyHandler(event) {
event = event || window.event;
if(event.keyCode==65 && event.ctrlKey) {
// ctrl+a was typed.
}
}
key codes:
shift 16
ctrl 17
alt 18
your jQuery:
$(document).keydown(function (e) {
if (e.keyCode == 18) {
alert("ALT was pressed");
}
});
JavaScript Madness: Keyboard Events
You can use the following:
document.onkeypress = function(evt) {
evt = evt || window.event;
etv = evt;
switch (etv.keyCode) {
case 16:
// Code to do when Shift presed
console.log('Pressed [SHIFT]');
break;
case 17:
// Code to do when CTRL presed
console.log('Pressed [CTRL]');
break;
case 32:
// Code to do when ALT presed
console.log('Pressed [ALT]');
break;
}
};
I needed a solution for this too, so found some stuff that worked, cleaned it up to be a lot less code, and ES6... JSFiddle link
function isCapsLock(event=window.event) {
const code = event.charCode || event.keyCode;
if (code > 64 && code < 91 && !event.shiftKey) {
return true;
}
return false;
}
document.getElementById("text").addEventListener("keypress", event => {
const status = document.getElementById("status");
if (isCapsLock(event)) {
status.innerHTML = "CapsLocks enabled";
status.style.color = "red";
} else {
status.innerHTML = "CapsLocks disabled";
status.style.color = "blue";
}
}, false);
<input type="text" id="text" /><br>
<span id="status"></span>
This is a very old question. gilly3's answer is valid only if we have at hand an event object of type KeyboardEvent passed as a function argument. How to detect the current control key state if we have not event object available such as in this function?
function testModifierKey() {
// have I some modifier key hold down at this running time?
}
I found the solution after a long search from https://gist.github.com/spikebrehm/3747378 of spikebrehm. his solution is tracing the modifier key state at any time using jQuery with a global variable.
The global variable window.modifierKey can be used in any circonstance without requiring event object.
function testModifierKey() {
// have I have some modifier key hold down at this executing time?
if(window.modifierKey) {
console.log("Some modifier key among shift, ctrl, alt key is currently down.");
// do something at this condition... for example, delete item without confirmation.
} else {
console.log("No modifier key is currently down.");
// do something at other condition... for example, delete this item from shopping cart with confirmation.
}
}
Here is his script to load in your HTML document:
// source: https://gist.github.com/spikebrehm/3747378
// modifierKey used to check if cmd+click, shift+click, etc.
!function($, global){
var $doc = $(document);
var keys;
global.modifierKey = false;
global.keys = keys = {
'UP': 38,
'DOWN': 40,
'LEFT': 37,
'RIGHT': 39,
'RETURN': 13,
'ESCAPE': 27,
'BACKSPACE': 8,
'SPACE': 32
};
// borrowed from Galleria.js
var keyboard = {
map: {},
bound: false,
press: function(e) {
var key = e.keyCode || e.which;
if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) {
keyboard.map[key].call(self, e);
}
},
attach: function(map){
var key, up;
for(key in map) {
if (map.hasOwnProperty(key)) {
up = key.toUpperCase();
if (up in keyboard.keys) {
keyboard.map[keyboard.keys[up]] = map[key];
} else {
keyboard.map[up] = map[key];
}
}
}
if (!keyboard.bound) {
keyboard.bound = true;
$doc.bind('keydown', keyboard.press);
}
},
detach: function() {
keyboard.bound = false;
keyboard.map = {};
$doc.unbind('keydown', keyboard.press);
}
};
$doc.keydown(function(e) {
var key = e.keyCode || e.which;
if (key === 16 || key === 91 || key === 18 || key === 17) {
modifierKey = true;
} else {
modifierKey = false;
}
});
$doc.keyup(function(e) {
modifierKey = false;
});
}(jQuery, window);
I am trying to build a hotkey into my web application in jQuery. I am trying to bind the Ctrl+U key stroke. Here is what I have:
$(document).keypress(function(e) {
if(e.ctrlKey && e.which == 117) {
if($("#nav-user-details").length > 0) {
$("#nav-user-details").find(".dropdown-menu").toggle();
}
}
});
This is not working though. How do I bind this key strokes?
Thanks.
Try this please http://jsfiddle.net/TN7GZ/
Press Ctrl+U and the screen will alert.
This will fit your need :)
Code
var isCtrl = false;
document.onkeyup=function(e){
if(e.which == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.which == 17) isCtrl=true;
if(e.which == 85 && isCtrl == true) {
//run code for CTRL+U -- ie, whatever!
alert('CTRL + U stuff');
return false;
}
}
I’m pretty sure 85 is the keycode for u, or am I missing something?
If you want mac support as well (the command key), it can get messy. I wrote a snippet before that might help you, but it involves browser detections (yuck):
var cmd = false;
$(document).on('keydown', function(e) {
if(detectMacCommand(e.which)) {
cmd = true;
return;
}
// now detect print (ctr/cmd + p)
if ( e.which == 85 && ( e.ctrl || cmd ) ) {
e.preventDefault();
alert('ctrl/cmd + u');
}
}).on('keyup', function(e) {
if(detectMacCommand(e.which)) {
cmd = false;
return;
}
});
function detectMacCommand(key) {
return ( $.browser.mozilla && key == 224 ||
$.browser.opera && key == 17 ||
$.browser.webkit && ( key == 91 || key == 93 ));
}
Demo: http://jsbin.com/afijam/2
$(document).keypress("u",function(e) {
if(e.ctrlKey)
alert("Ctrl+U was pressed!!");
});
You'll have to use keydown instead of keypress. Keypress does not trigger for non-char keys.
$(document).keydown(function (e) {
if (e.ctrlKey && e.which === 81) {
alert("key pressed");
return false;
}
});
Try this:
var prevKey = null;
$(document).keydown(function (e) {
var thisKey = e.which;
if (prevKey && prevKey == 17) {
if (thisKey == 85) {
// Your code.
}
}
prevKey = thisKey;
});
If you are working in a Xhtml file and you get an error The entity must immediately follow the & then you should use &&& instead of &&.