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;
}
}
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!")
}
}
I try to detect if a user presses F12 or ALT + L.
document.onkeydown = function (event) {
event = (event || window.event);
if (event.keyCode == 123 || (event.keyCode == 18 && event.keyCode == 76)) {
//do anything
return false;
}
}
What am I doing wrong?
event.keyCode contains only one value. You can use event.altKey do detect if the alt key is pressed.
document.onkeydown = function (event) {
event = (event || window.event);
if (event.keyCode == 123 || (event.keyCode === 76 && event.altKey)) {
//do something
return false;
}
}
The standard way is to create a bool to detect if the 'alt' key is currently held down and then a separate if to detect if that is true and if the L key as just been pressed - see the fiddle:
http://jsfiddle.net/L4cb9/1
var held = false;
...
else if (event.keyCode == 18) {held = true;}
if (held == true && event.keyCode == 76) {
alert();
}
...
document.onkeyup = function(event) {
if (event.keyCode == 18) {held = false;}
}
This is applicable to holding any combination of keys - you can create an array for multiple key holds greater than two:
held = [];
...
if (event.keyCode == i) {held[i] = true;}
...
and so on
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?
I'm looking for a KeyListener for a game I'm developing in JavaScript. I have no idea how this would work in real code but it would be something like this:
if(keyPress == upKey)
{
playerSpriteX += 10;
}
else if(keyPress == downKey)
{
playerSpriteY -= 10;
}
etc...
I searched it up, and Google came up with things that involved AJAX which I don't understand yet. Is there a built in function in JavaScript that does this?
Here's an update for modern browsers in 2019
let playerSpriteX = 0;
document.addEventListener('keyup', (e) => {
if (e.code === "ArrowUp") playerSpriteX += 10
else if (e.code === "ArrowDown") playerSpriteX -= 10
document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;
});
Click on this window to focus it, and hit keys up and down
<br><br><br>
<div id="test">playerSpriteX = 0</div>
Original answer from 2013
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 38) {
playerSpriteX += 10;
}else if (key == 40) {
playerSpriteX -= 10;
}
}
FIDDLE
The code is
document.addEventListener('keydown', function(event){
alert(event.keyCode);
} );
This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)
JSFIDDLE DEMO
If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup
window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 38) { //up key
alert('up');
} else if (code === 40) { //down key
alert('down');
}
};
Did you check the small Mousetrap library?
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.
A bit more readable comparing is done by casting event.key to upper case (I used onkeyup - needed the event to fire once upon each key tap):
window.onkeyup = function(event) {
let key = event.key.toUpperCase();
if ( key == 'W' ) {
// 'W' key is pressed
} else if ( key == 'D' ) {
// 'D' key is pressed
}
}
Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))
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);