I'm using a open-source game and I'm trying ( for exercise ) to modify it so it can run on Android. The problem is :
In the original game you use space to jump and I need the game to respond to a tactil event so the charachter can actually jump.
The game use this code to keep track of spacebar events :
var KEY_CODES = {
32: 'space'
};
var KEY_STATUS = {};
for (var code in KEY_CODES) {
if (KEY_CODES.hasOwnProperty(code)) {
KEY_STATUS[KEY_CODES[code]] = false;
}
}
document.onkeydown = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = true;
}
};
document.onkeyup = function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
if (KEY_CODES[keyCode]) {
e.preventDefault();
KEY_STATUS[KEY_CODES[keyCode]] = false;
}
};
// jump higher if the space bar is continually pressed
if (KEY_STATUS.space && jumpCounter) {
player.dy = player.jumpDy;
}
So how can I transform the touch event in a spacebar event ?
Thanks in advance for helping, I'm new to coding and I'm trying to learn :)
You could add the following piece of code to your script, to simulate spacebar events from touch events.
document.addEventListener("touchstart", function(e) {
document.onkeydown({ keyCode: 32 });
});
document.addEventListener("touchend", function(e) {
document.onkeyup({ keyCode: 32 });
});
Related
I try to prevent the default zoom event and trigger a function instead.
I managed to do it for the default save event (CTRL+S) across browsers:
document.documentElement.addEventListener('keydown', function(e) {
e = e || window.event;
var keynum;
if (window.event) {
keynum = e.keyCode;
} else if (e.which) {
keynum = e.which;
if (e.ctrlKey) {
switch (String.fromCharCode(keynum)) {
case 'S':
console.log('CTRL S pressed');
e.preventDefault ? e.preventDefault() : (e.returnValue = false);
break;
}
}
}
});
https://codepen.io/anon/pen/NjRbaa?editors=1010
However, CTRL++ seems more tricky since there is no cross browser keyCode for the "+" sign. I tried to use keypress instead of keydown but then the default isn't prevented in Chrome and IE.
https://github.com/jeresig/jquery.hotkeys Try this :)
$(document).on('keydown', null, 'ctrl+s', fn);
I've looked on the internet for this and all I can find are depreciated functions so before posting please check to make sure that the code you suggest isn't depreciated.
I've found this and tried it:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
$(document).ready(function () {
var x = new KeyboardEvent("FormatCode", deprectiatedArgument);
});
But after further inspection the KeyboardEventInit is depreciated.
I would like to create an event on pres of the CTRL + K keys.
You have a specific key code for every button on the keyboard.
All of them are here http://keycode.info/.
$(document).keyup(function(e) {
if (e.keyCode === 13) function(); // enter
if (e.keyCode === 27) function(); // esc
});
Here's a vanilla JS solution to detect a CTRL + k keypress event:
UPDATED to also trigger the event.
document.addEventListener("keypress", function(e) {
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 11 || e.keyCode == 75)) {
alert("ctrl+k!");
}
});
document.getElementById("trigger").addEventListener("click", function(){
//trigger a keypress event...
var e = document.createEvent('HTMLEvents');
e.initEvent("keypress", false, true);
e.ctrlKey = true;
e.keyCode = 75;
document.dispatchEvent(e);
});
Press <kbd>ctrl+k</kbd> or
trigger the event
you can use a library called shortcut.js .. here is a link to their source code for downloading:
http://www.openjs.com/scripts/events/keyboard_shortcuts/shortcut.js
then run ur code by making this function:
shortcut.add("Ctrl+K",function() {
alert("Hi there!");
});
and here is the documentation : http://www.openjs.com/scripts/events/keyboard_shortcuts/
hope that can help.
$(document).ready(function () {
var bool = false;
$(document).keydown(function (e) {
if (e.keyCode === 17) {
bool = true;
}
if (bool == true && e.keyCode == 75) {
alert("");
}
});
$(document).keyup(function (e) {
if (e.keyCode === 17) {
bool = false;
}
});
});
This is how me and a friend got it working
I write this Javascript code but it doesn't disable 2 windows keys (I mean logo key and menu key), though:
document.onkeydown = function(e) {
document.title = e.keyCode;
if (e.keyCode == 91 || e.keyCode == 93) {
window.event.keyCode = 0;
window.event.returnValue = false;
return false;
}
};
the 2 window.xxx statements are actually not necessary but I add them in to buy an insurance (Just doubt that e doesn't totally equal to window.event).
So I'd like to ask this question: " Is there a feasible way, directly or indirectly, to do this job in Javascript? "
Your code looks right, try to find out real keycodes with this simple script:
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
alert("keycode: " + keycode);
}
And to disabel certain keys you modify function (example for 'Enter'):
document.onkeydown = checkKeycode
function checkKeycode(e) {
var event = e || window.event;
var keycode = event.which || event.keyCode;
if (keycode == 13) {
// return key was pressed
}
}
JavaScript cannot stop the effect of the Windows logo key, which (when released) is supposed to bring up the Window's start menu. In combination with other keys, it has other system wide effects (like with M = minimise all windows). This is something that happens outside of the browser context, and thus cannot and should not be blocked by the code running in your browser.
The Windows menu key can be somewhat disabled, as described in this answer:
$(function(){
var lastKey=0;
$(window).on("keydown", document, function(event){
lastKey = event.keyCode;
});
$(window).on("contextmenu", document, function(event){
if (lastKey === 93){
lastKey=0;
event.preventDefault();
event.stopPropagation();
return false;
}
});
});
I've been trying to program a pingpong game without jQuery (challenge from Software Design teacher), and am planning on using onkeypress to move the paddles. However, I'm not sure how to attach a specific key to the function specified in the event handler.
It's not terribly relevant, but here's my code:
HTML:
<div id="Paddle1" class="paddle" onkeypress="PaddleMovement1(event)"></div>
<div id="Paddle2" class="paddle" onkeypress="PaddleMovement3(event)"></div>
JavaScript:
var PaddleMovement1 = function(){
document.getElementById('Paddle1Up').style.animationPlayState="running";
setTimeout(Paddle1Stop1, 25)
var Paddle1Stop1 = function(){
document.getElementById('Paddle1Up').style.animationPlayState="paused";
};
};
var PaddleMovement2 = function(){
document.getElementById('Paddle1Down').style.animationPlayState="running";
setTimeout(Paddle1Stop2, 25)
var Paddle1Stop2 = function(){
document.getElementById('Paddle1Down').style.animationPlayState="paused";
};
};
var PaddleMovement3 = function(){
document.getElementById('Paddle2Up').style.animationPlayState="running";
setTimeout(Paddle2Stop1, 25)
var Paddle2Stop1 = function(){
document.getElementById('Paddle2Up').style.animationPlayState="paused";
};
};
var PaddleMovement4 = function(){
document.getElementById('Paddle2Down').style.animationPlayState="running";
setTimeout(Paddle2Stop2, 25)
var Paddle2Stop2 = function(){
document.getElementById('Paddle2Down').style.animationPlayState="paused";
};
};
Finally, the complete thing can be found in this jsfiddle:
http://jsfiddle.net/2RfzF/2/
keypress is only fired for keypresses that result in typeable characters, not other keys. To detect other keys, use keydown and keyup. This should be fairly clear from the specification:
A user agent must dispatch this event when a key is pressed down, if and only if that key normally produces a character value.
This page is a handy guide to the madness that is keyboard events in JavaScript across browsers...
Separately, for your purposes I'd probably trap the events on document rather than on a specific element (keydown and keyup bubble, so that works).
For example:
(function() {
if (document.addEventListener) {
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keydown", keyUpHandler, false);
}
else if (document.attachEvent) {
document.attachEvent("onkeydown", function() {
keyDownHandler(window.event);
});
document.attachEvent("onkeydown", function() {
keyUpHandler(window.event);
});
}
else {
// If you want to support TRULY antiquated browsers
document.onkeydown = function(event) {
keyDownHandler(event || window.event);
};
document.onkeyup = function(event) {
keyUpHandler(event || window.event);
};
}
function keyDownHandler(e) {
var key = e.which || e.keyCode;
display("keydown: " + key);
}
function keyDownHandler(e) {
var key = e.which || e.keyCode;
display("keyup: " + key);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
Live Copy | Source
Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode