When dealing with a lot of possible keyCode (ex : for hotkeys), we'd like to use a switch statement.
We don't want to prevent all combinations of Ctrl + another key to preserve other constructor hotkeys.
We'd like to prevent the default action only for defined cases. But how to do that once ?
I think I'm missing something really obvious.
document.addEventListener("keydown", function(e) {
var key = e.keyCode || e.which;
if (!e.ctrlKey) return false;
switch(key) {
case 109: e.preventDefault(); scale(-1); break;
case 107: e.preventDefault(); scale(1); break;
case 96: e.preventDefault(); scale(0);break;
case 78: e.preventDefault(); newFile();break;
case 79: e.preventDefault(); openFile();break;
case 80: e.preventDefault(); printFile();break;
case 83: e.preventDefault(); saveFile();break;
case 66: e.preventDefault(); command("bold");break;
case 73: e.preventDefault(); command("italic");break;
case 85: e.preventDefault(); command("underline");break;
case 76: e.preventDefault(); command("justifyLeft");break;
case 69: e.preventDefault(); command("justifyCenter");break;
case 82: e.preventDefault(); command("justifyRight");break;
case 74: e.preventDefault(); command("justifyFull");break;
case 90: e.preventDefault(); clipboard.undo();break;
case 89: e.preventDefault(); clipboard.redo();break;
default: console.log("Key pressed n°", key)
}
}, false);
You can simply use a variable prevent that is only set to true in the default case. Then do e.preventDefault() after the switch statement, as follows:
document.addEventListener("keydown", function(e) {
var key = e.keyCode || e.which;
if (!e.ctrlKey) return false;
var prevent = true;
switch(key) {
case 109: scale(-1); break;
case 107: scale(1); break;
case 96: scale(0);break;
case 78: newFile();break;
case 79: openFile();break;
case 80: printFile();break;
case 83: saveFile();break;
case 66: command("bold");break;
case 73: command("italic");break;
case 85: command("underline");break;
case 76: command("justifyLeft");break;
case 69: command("justifyCenter");break;
case 82: command("justifyRight");break;
case 74: command("justifyFull");break;
case 90: clipboard.undo();break;
case 89: clipboard.redo();break;
default: prevent = false; console.log("Key pressed n°", key); break;
}
if (prevent) e.preventDefault();
}, false);
Related
i want to change the way my Js game works, basically the game does not recognize input whenever the language is not english with no Capital letters ( only when the event.key is equal to wasd ) how can i fix this bug ?
thanks !
window.addEventListener('keydown', (event) => {
if (!player.isDead){
switch (event.key) {
case 'w':
keys.d.pressed = true;
player.lastkey = 'd';
break;
case 'a':
keys.a.pressed = true;
player.lastkey = 'a';
break;
case 'w':
if(player.position.y > 0)
{
player.velocity.y = -10;
}
break;
case ' ':
player.Attacking();
if(player.lastkey === 'd'){player.SwitchSprite('punch')}
else{player.SwitchSprite('fpunch')}
break;
}
}
You should use the event.code or event.keyCode properties to stay language independent;
switch (event.code) // <- not event.key
case "KeyW": // <- not 'w'
...
E.g. I have the following script
<script>
document.onkeydown = function(evt){
evt = evt || window.event;
switch (evt.keyCode){
case 67:
createNewFile();
break;
case 82:
goToRecords();
break;
case 84:
goToToday();
break;
case 36:
goToMsHome();
break;
case 27:
escToCloseOptions();
break;
case 83:
summary();
break;
case 73:
insertRecord();
break;
}
};
</script>
When I press
shift + keycode
to call a function specified, I am just new to JavaScript and I code JavaScript based on other languages I know
Thanks and Regards
Check .shiftKey which returns a boolean indicating if the key is pressed. Placing this conditional around your switch will prevent any events from occurring unless the key is pressed in combination with shift.
document.onkeydown = function(evt){
evt = evt || window.event;
if(evt.shiftKey){
switch (evt.keyCode){
case 67:
createNewFile();
break;
case 82:
goToRecords();
break;
case 84:
goToToday();
break;
case 36:
goToMsHome();
break;
case 27:
escToCloseOptions();
break;
case 83:
summary();
break;
case 73:
insertRecord();
break;
}
}
};
You can detect the shift key separately. e.g. if you want to call createNewFile with the shift key down:
if(evt.shiftKey && evt.keyCode == 67) {
createNewFile();
}
In your code, you could do something like:
evt = evt || window.event;
switch (evt.keyCode){
case 67:
if (evt.shiftkey) {
// Do something special for shift mode.
} else {
createNewFile();
}
break;
...
I'm programming something withe Javascript which captures keyboard input, but the problem is that every time the user presses a key there an error sound. How can I disable it?
#Polaris878
function KeyPressed(e)
{
if (!e) e = window.event;
if (e.which)
{
keycode = e.which
}
else if (e.keyCode)
{
keycode = e.keyCode
}
switch (keycode)
{
case 49:
key = "1";
break;
case 50:
key = "2";
break;
case 51:
key = "3";
break;
case 52:
key = "4";
break;
case 53:
key = "5";
break;
case 54:
key = "6";
break;
case 55:
key = "7";
break;
case 56:
key = "8";
break;
case 57:
key = "9";
break;
case 48:
key = "0";
break;
default:
key = "";
return false;
break
}
if (keys == "NULL")
{
keys = key
}
else
{
keys = keys + key
} if (keys.length >= 5)
{
document.formular.submit();
}
document.formular.code.value = keys;
}
var keys = "";
document.onkeydown = KeyPressed
How can i make a movement of a element while the user is "keydown" and then if he make "keyup" to stop the animation(movement), this is my code by now
$(document).ready(function(){
function checkKey(e){
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
if ($.browser.mozilla) {
$(document).keydown (checkKey);
} else {
$(document).keydown (checkKey);
}
})
i want to move the cube while the user press the key (down, left, up, right), not with every press, is possible?
You need a simple 2D engine that will setup a game loop.
Simple demo: http://jsfiddle.net/kzXek/
Source: https://github.com/superrob/simple-2D-javascript-engine/blob/master/simple2d.html
Is that you are looking for?
$(document).on("keyup", function() {
$("#cube").stop(true);
});
DEMO: http://jsfiddle.net/LjGRe/
you can just change the checkKey function, and add this to it :
function checkKey(e){
$(document).keyup(return);
switch (e.keyCode) {
case 40:
//alert('down');
$('#cube').animate({top: "+=20px"})
break;
case 38:
//alert('up');
$('#cube').animate({top: "-=20px"})
break;
case 37:
//alert('left');
$('#cube').animate({left: "-=20px"})
break;
case 39:
//alert('right');
$('#cube').animate({left: "+=20px"})
break;
default:
alert('???');
}
}
I think using a timer to handle the animation is better.
You just start the timer when a key is pressed and stop it when the key is released ..
Here is a simple solution that handles multiple keypresses (can move diagonally)
var direction = {top:0,left:0},
animator = null,
cube = $("#cube");
function animate(){
cube.css({
top: '+=' + direction.top,
left: '+=' + direction.left
});
}
function setProperties(keyCode, unset){
switch (keyCode) {
case 40:
direction.top = (unset)?0:2;
break;
case 38:
direction.top = (unset)?0:-2;
break;
case 37:
direction.left = (unset)?0:-2;
break;
case 39:
direction.left = (unset)?0:2;
break;
}
}
function setKey(e) {
setProperties(e.keyCode);
if (animator === null){
animator = setInterval(animate, 10);
}
}
function unsetKey(e){
setProperties(e.keyCode, true);
if (direction.top === 0 && direction.left === 0){
clearTimeout(animator);
animator = null;
}
}
$(document)
.on("keyup", unsetKey)
.on('keydown', setKey);
Demo at http://jsfiddle.net/gaby/Cu6nW/
For some very odd reason when you press keys in the order of forward, spacebar, and left. Left does not fire and returns spacebar instead. Any other combination of three keys works perfectly fine, but not that one. Any clues as to why?
var Ctrl = {
init: function() {
window.addEventListener('keydown', this.keyDown, true);
window.addEventListener('keyup', this.keyUp, true);
},
keyDown: function(event) {
console.log(event.keyCode);
switch(event.keyCode) {
case 37: // Left
Ctrl.left = true;
break;
case 39: // Right
Ctrl.right = true;
break;
case 38: // up
Ctrl.up = true;
break;
case 40: // down
Ctrl.down = true;
break;
case 32:
Ctrl.space = true;
break;
default:
break;
}
},
keyUp: function(event) {
switch(event.keyCode) {
case 37: // Left
Ctrl.left = false;
break;
case 39: // Right
Ctrl.right = false;
break;
case 38:
Ctrl.up = false;
break;
case 40:
Ctrl.down = false;
break;
case 32:
Ctrl.space = false;
break;
default:
break;
}
}
};
Maybe one of your keys is activating an unwanted default behavior. You can try to add event.preventDefault(); to your event bindings.
check the jsFiddle
It depends on model of your keyboard. Some keyboards doesn't work with some key combinations. It's normal.