How to simulate multiple keypress event at the same time - javascript

I found this way, but with it I can only set one keycode in .which, I want to simulate the keys ALT+space+x at the same time.
For ALT I can use .altKey = true;
$(".btn").click(function() {
var e = jQuery.Event("keypress");
e.which = 88; // x code value
e.altKey = true; // Alt key pressed
$("input").trigger(e);
});
How do I add space keycode?

I apologize for my previous answer. I thought about how to handle. Now I modify code to handle and trigger:
You can implement it with two events: keyDown and keyUp like this:
var x,
alt,
space;
document.addEventListener('keydown', function (e) {
e = window.event ? event : e;
switch (e.keyCode) {
case 88:
x = true;
break;
case 18:
alt = true;
break;
case 32:
space = true;
break;
}
});
document.addEventListener('keyup', function (e) {
if (x && alt && space) {
alert("alt + space + x Pressed!");
}
x = alt = space = false;
});
function triggerEvent(eventName, keyCode) {
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.keyCode = keyCode || null;
if (document.createEvent) {
document.dispatchEvent(event);
} else {
document.fireEvent('on' + event.eventType, event);
}
}
triggerEvent('keydown', 88);
triggerEvent('keydown', 18);
triggerEvent('keydown', 32);
triggerEvent('keyup');
https://jsfiddle.net/m83omwq5/1/

Related

Google Map API on Web Rotate and Tilt Map With Mouse

I am trying to Tilt and Rotate Google Map with mouse right click.
I followed the documentation
https://developers.google.com/maps/documentation/javascript/webgl/tilt-rotation#maps_webgl_tilt_rotation-css
but find no help yet to achieve same thing with mouse movement.
google Api provide shift + drag mouse to tilt and rotate but I do not wanted to use shift button
only mouse
An bypass I tried was that on mouse drag create keyboard Event key down of shift key and keep rotating mouse but that did not work,
shift key is pressed by right click but map did not get that
that code is here
document.body.addEventListener("keydown", (e) => {
if (e.key == "Enter") {
console.log('Enter keydown');
let keyEvent = new KeyboardEvent("keydown", { shiftKey: true});
document.body.dispatchEvent(keyEvent);
}
if(e.shiftKey) {
console.log('Shift Key keydown');
}
if (e.key == "Enter" && e.shiftKey) {
console.log('Enter + Shift Key keydown');
}
});
document.body.addEventListener("keyup", (e) => {
if (e.key == "Enter") {
console.log('Enter keyup');
let keyEvent = new KeyboardEvent("keyup", { shiftKey: true});
document.body.dispatchEvent(keyEvent);
}
if(e.shiftKey) {
console.log('Shift Key keyup');
}
if (e.key == "Enter" && e.shiftKey) {
console.log('Enter + Shift Key keyup');
}
});
document.body.addEventListener("keypress", (e) => {
if (e.key == "Enter") {
console.log('Enter keypress');
let keyEvent = new KeyboardEvent("keypress", { shiftKey: true});
document.body.dispatchEvent(keyEvent);
}
if(e.shiftKey) {
console.log('Shift Key keypress');
}
if (e.key == "Enter" && e.shiftKey) {
console.log('Enter + Shift Key keypress');
}
});
map.addListener("drag", () => {
let keyEvent = new KeyboardEvent("keydown", { shiftKey: true});
document.body.dispatchEvent(keyEvent);
});
map.addListener("dragend", () => {});
$('#map').mousedown(function(event) {
switch (event.which) {
case 1:
console.log('Left Mouse button pressed.');
break;
case 2:
console.log('Middle Mouse button pressed.');
break;
case 3:
console.log('Right Mouse button pressed.');
const keyEvent = new KeyboardEvent("keydown", { shiftKey: true});
document.body.dispatchEvent(keyEvent);
break;
default:
console.log('You have a strange Mouse!');
}
});
from above code on shift key press or mouse right click i am able to get console log that shift key is pressed but how to rotate map on that no idea
I found a way now, in which we get mouse move position and on basis of it update the map tilt or heading
here is sample code
var directionx = "";
var directiony = "";
let oldx = 0;
let oldy = 0;
document.addEventListener('mousemove', function(e) {
var rightclk = false;
if(e.which) {
rightclk = (e.which == 3);
}
if(rightclk == true){
if(e.pageX == oldx){
}else{
if (e.pageX < oldx) {
directionx = 'left';
} else if (e.pageX > oldx) {
directionx = 'right';
}
oldx = e.pageX;
if(directionx == 'left'){
map.setHeading(map.getHeading()-3);
}
if(directionx == 'right'){
map.setHeading(map.getHeading()+3);
}
}
if(e.pageY == oldy){
}else{
if (e.pageY < oldy) {
directiony = 'up';
} else if (e.pageY > oldy) {
directiony = 'down';
}
oldy = e.pageY;
if(directiony == 'up'){
map.setTilt(map.getTilt()+3);
}
if(directiony == 'down'){
map.setTilt(map.getTilt()-3);
}
}
}
});

How to handle pressing C+/ keys on JS(key combination) and invoke some function?

const cKeycode = 67;
const SlashKeyCode = 191;
document.onkeyup = function(e){
var e = e || window.event;
if(e.keyCode==cKeycode && e.which == SlashKeyCode) {
alert("C+/ pressed");
return false;
}
}
I've just tried this one and many other variants but I can't handle this. Maybe someone know the better way
Your code doesn't work because the event only passes one key at a time (excluding keys like ctrl and alt). To get around this, we can store if either key is pressed, then check this once the second key is pressed. This method works whether the user presses c then /, or if they press / then c.
const keys = ["c", "/"];
var pressedKey = -1;
document.onkeydown = function(e){
var e = e || window.event;
let key = e.key;
if (keys.indexOf(key) > -1) {
if (pressedKey === -1) pressedKey = key;
else if (pressedKey !== key) console.log("C + / pressed");
}
}
document.onkeyup = function(e) {
let key = e.key;
if (key === pressedKey) pressedKey = -1;
}
The onkeyup event doesn't return a collection of pressed keys - it just returns a single key at a time. Furthermore onkeyup just fires if you actually release a key so if you want to know when two keys are pressed you need to utilize the onkeydown event.
To do this create a global boolean variable which states if the first button is actually pressed and if it is, check if the second key is pressed as well.
Here's an example. For simplicity I'm using the a and e key.
const AKeycode = 65;
const EKeycode = 69;
let AKeycodeDown = false;
let EKeycodeDown = false;
document.onkeydown = function(e) {
if (e.keyCode == AKeycode) {
AKeycodeDown = true;
}
if (e.keyCode == EKeycode) {
EKeycodeDown = true;
}
if (AKeycodeDown && e.keyCode == EKeycode || EKeycodeDown && e.keyCode == AKeycode) {
AKeycodeDown = false;
EKeycodeDown = false;
alert("A+E pressed");
}
}
document.onkeyup = function(e) {
if (e.keyCode == AKeycode) {
AKeycodeDown = false;
}
if (e.keyCode == EKeycode) {
EKeycodeDown = false;
}
}

Key pressed and click in the same time

how can I merge keypress and on click? I mean when a user press enter and click somewhere in the same time I need to invoke a function.
$(document).keypress(function(e) {
var code = e.keyCode || e.which;
if(code == 13) {
alert('keypress');
}
});
$(document).on( "click", function() {
alert('click');
});
I have this code but I am not able to merge it (usually I don't work with jQuery/javascript).
Something like this may do the trick
var pressingEnter = false;
$(document).on({
keydown: function(e) {
if(e.which == 13) {
// enter is being pressed, set true to flag variable
pressingEnter = true;
}
},
keyup: function(e) {
if(e.which == 13) {
// enter is no longer pressed, set false to flag variable
pressingEnter = false;
}
},
click: function() {
if (pressingEnter) {
console.log('click and enter pressed');
}
}
});
BTW: there is no need to do var code = e.keyCode || e.which; since jQuery resolves that for you. You can use e.which on any browser.
EDIT
This version should allow any order of key pressed / mouse click. I'm assuming only left click is captured. Logic to handle enter + mouse click is placed on keydown and mousedown (it could be moved to keyup and mouseup if makes more sense)
Changed alert by console.log since the first prevents mouseup event to be triggered. Nowdays we have hundred of better ways to show a message to user than built-in alert pop ups so I'll assume making it work for it is not a requirement.
var pressingEnter = false;
var clickingMouseButton = false;
$(document).on({
keydown: function(e) {
if(e.which == 13) {
pressingEnter = true;
}
if (clickAndEnterPressing()) {
console.log('click and enter pressed');
}
},
keyup: function(e) {
if(e.which == 13) {
pressingEnter = false;
}
},
mousedown: function(e) {
if (e.which == 1) {
clickingMouseButton = true;
}
if (clickAndEnterPressing()) {
console.log('click and enter pressed');
}
},
mouseup: function(e) {
if (e.which == 1) {
clickingMouseButton = false;
}
}
});
function clickAndEnterPressing() {
return pressingEnter && clickingMouseButton;
}
Here's an example that will work if enter is pushed first or if the mouse is clicked first or if they are both pressed within a certain threshold of time apart (I set it to 100 ms, but this can be easily adjusted):
var enterDown = false;
var mouseDown = false;
var lastEnter = false;
var lastMouseUp = false;
var triggerOnNextUp = false;
$(document).on({
keydown: function(e) {
enterDown = true;
},
keyup: function(e) {
if(e.which == 13) {
lastEnter = (new Date()).getTime();
enterDown = false;
detectEnterAndClick();
if (mouseDown) {
triggerOnNextUp = true;
}
}
},
mousedown: function() {
mouseDown = true;
},
mouseup: function() {
lastMouseUp = (new Date()).getTime();
mouseDown = false;
detectEnterAndClick();
if (enterDown) {
triggerOnNextUp = true;
}
}
});
function detectEnterAndClick() {
if (Math.abs(lastEnter - lastMouseUp) < 100 || triggerOnNextUp) {
// Reset variables to prevent from firing twice
triggerOnNextUp = false;
enterDown = false;
mouseDown = false;
lastEnter = false;
lastMouseUp = false;
$("body").append("Clicked and pushed enter<br>");
}
}
See it on JSFiddle
There is no way to 'merge' events. However you could for example debounce your handler. For example (using lodash):
var handler = _.debounce(function(event) { alert(event.type); }, 100);
$(document)
.on('click', handler)
.on('keypress', handler);
you can use the event.type to determine what triggered the event
Demo
$(function(){
$(document).on("click", ClickAndKeyPress);
$(document).on("keypress", ClickAndKeyPress);
});
function ClickAndKeyPress(event){
$("div").text(event.type);
}

Change character when keydown is held

I am trying to make a simple way to change a character in an input field when the key is held down for more than 1second. For example holding down a would then change the character to á.
The exact thing I am looking to do can be seen on fluencia.com.
Also there is a need to be able to change the character if it is held for a further second.
So far, all I have done is detect the key held with the following code:
count = 0;
$(document).bind('keypress', function(e){
keyisdown = false;
key = e.which
if (e.which === key) {
keyisdown = true;
count ++;
if(count>1){
}
}
}).bind('keyup',function(){
keyisdown = false;
count = 0;
console.log('key up');
});
Thanks
Adam
This should do it for key "a".. You'll need to look up your keycode
var fired = false;
$(document).on("keydown", function(e) {
if (e.keyCode == 65) {
var timer = setTimeout(function() {
if (!fired) console.log('its held');
fired = true;
}, 1000);
$(document).on("keyup", function() {
clearTimeout(timer);
});
}
});
fiddle - http://jsfiddle.net/0a9rftt2/
With help from Graham T above and a bit of playing around I come up with the following:
var fired = false;
var keycode = null;
var key = null;
$("#loginEmail").on("keypress", function(e) {
keycode = e.which;
key = String.fromCharCode(keycode);
});
$("#loginEmail").on("keydown", function(e) {
var s = this.value;
var str = this.value;
if (e.keyCode == 65) {
var timer = setTimeout(function() {
if (!fired) console.log('its held');
fired = true;
if(fired){
s = $("#loginEmail").val();
str = s.substring(0, s.length - 1);
replacewith = 'á';
str = str+replacewith;
$("#loginEmail").val(str);
}
}, 500);
$(document).on("keyup", function() {
clearTimeout(timer);
fired = false;
});
}
});
It is not cleaned up as yet. I had to use keypress to get the true character (capitalised or not) and then used keydown to detect key being held down.

javascript keypress to control animation

Space Invader game: I want to control the 'base gun' (move it left and right and fire missiles at the invaders. So I need a keypress or (keydown?) event to change a variable (x coordinate) and a key press event to fire a missile.
Can anyone show me how the keypress event is detected and the variable is changed?
document.onkeydown = function(e) {
var key = e.keyCode;
if (key===37) {//left arrow pressed
} else if (key===39) {//right arrow pressed
}
}
Like this?
document.onkeydown = checkKey;
var xCoord = 100;
function checkKey(e) {
e = e || window.event;
switch (e.keyCode) {
case 37 : // left
xCoord -= 5;
break;
case 39 : // right
xCoord += 5;
break;
}
}
Exciting fiddle: http://jsfiddle.net/u5eJp/
Couple things I would like to add to the other answers:
1) Use constants to make it easier on yourself
2) There is no way to check if a key is currently pressed in javascript, so you should keep track of what is currently pressed as well
var pressed = {
up: false,
down: false,
left: false,
right: false
};
var LEFT_ARROW = 37;
var UP_ARROW = 38;
var RIGHT_ARROW = 39;
var DOWN_ARROW = 40;
document.onkeydown = function (e) {
e = e || window.event;
switch (e.keyCode) {
case LEFT_ARROW:
pressed.left = true;
break;
case UP_ARROW:
pressed.up = true;
break;
case RIGHT_ARROW:
pressed.right = true;
break;
case DOWN_ARROW:
pressed.down = true;
break;
default:
break;
}
}
//update position separately
function updatePos() {
if (pressed.up) { //change y up }
if (pressed.down) { //change y down }
if (pressed.left) { //change x left }
if (pressed.right) { //change x right }
}
Hope this helps, and good luck!

Categories