HTML5, CSS, and JavaScript Game creating - javascript

I have a game I made with HTML5, CSS, and JavaScript. I have HTML image tags of joystick arrows. I would like users to be able to click my joystick arrow images with the mouse and have it work as if the arrows on the keyboard were pressed. How do I make keyCode 39 fire when the image of the right arrow is clicked? I wrote the code like this but it doesn't work:
var $rt_arrow = $('.rt_arrow')
$rt_arrow.on('click' , function (e) {
e.keyCode == 39
})

You are facing an XY problem.
You don't want to trigger a keyboard event in this case, you just want your mouse event to trigger the same action as your keyboard event.
That is make you code more modular and create functions for each actions, then you can make your handlers call the required function:
onkeydown = e => {
if(e.key === 'ArrowLeft') goLeft();
else if(e.key === 'ArrowRight') goRight();
// ...
};
onclick = e => {
if(e.target === left_arrow) goLeft();
else if(e.target === right_arrow) goRight();
// ...
};

I believe this is what you're looking for http://www.port135.com/2017/12/24/how-to-simulate-keyboard-key-press-in-javascript-using-jquery/
I haven't tested this so I'm not 100% sure, though it seems pretty straight-forward.
So instead of:
e.keyCode == 39
Put:
jQuery.event.trigger({ type: 'keydown', which: 39 });

Related

How to move caret «home» or «end» use fn+arrow key JavaScript

How to repeat behaviour CMD+arrowLeft (Home) and CMD+arrowRight (End) for fn+arrowLeft and fn+arrowRight as well.
Please write code if existed another approach to move caret (cursor) to the begin or to the end of input field use combination of keys. I use MacOs.
36 - event.key for fn+arrowLeft
35 - event.key for fn+arrowRight
const handleKey = (e) => {
if (e.metaKey || e.altKey || e.ctrlKey) {
e.preventDefault();
}
if (e.key === 'Home') {
// code here
}
if (e.key === 'End') {
// code here
}
};
<input type="text" onkeydown="handleKey()">
As alternative way but doesn’t cover my need:
Set keyboard caret position in html textbox
I assumed that good way but don’t know how use right KeyboardEvent object:
how to set keycode value while triggering keypress event manually in pure javascript?

Remap the Control + S button in javascript (or jquery)

I've been having troubles with the Control + S button, I would like to remap the Control + S button to something else instead of the save page as window.
** I know that its not possible to disable it**
I want the functionality like what https://www.hastebin.com/ has, where if you control + s it does an action. I've already tried
$(window).keypress((e) => {
if (!(e.which == 115 && e.ctrlKey) && !(e.which == 19)) return true;
console.log('bruh');
e.preventDefault();
return false;
});
That DOES work, but the save as page still shows up, where as on hastebin, it does not when you do ctrl + S
Any ideas?
Use keydown rather than keypress:
$(window).on("keydown", (e) => {
if (e.key === "s" && e.ctrlKey) {
console.log("Ctrl+S");
e.preventDefault();
}
});
<div>Click here, then press Ctrl+S</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In that example I've used the key property rather than the deprecated which property, but if you need to support obsolete browsers you could use which (perhaps as a fallback).
CTRL+S fires keydown event, not keypress event AFAIK.
$(window).on("keydown", (e) => {
if (e.key === "s" && e.ctrlKey) e.preventDefault();
});

How to submit the form when pressing Ctrl + S (instead of "save the webpage") in JavaScript? [duplicate]

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

How do I capture a CTRL-S without jQuery or any other library?

How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});

Prevent default behavior in text input while pressing arrow up

I’m working with basic HTML <input type="text"/> text field with a numeric value.
I’m adding JavaScript event keyup to see when user presses arrow up key (e.which == 38) – then I increment the numeric value.
The code works well, but there’s one thing that bugs me. Both Safari/Mac and Firefox/Mac move cursor at the very beginning when I’m pressing the arrow up key. This is a default behavior for every <input type="text"/> text field as far as I know and it makes sense.
But this creates not a very aesthetic effect of cursor jumping back and forward (after value was altered).
The jump at the beginning happens on keydown but even with this knowledge I’m not able to prevent it from occuring. I tried the following:
input.addEventListener('keydown', function(e) {
e.preventDefault();
}, false);
Putting e.preventDefault() in keyup event doesn’t help either.
Is there any way to prevent cursor from moving?
To preserve cursor position, backup input.selectionStart before changing value.
The problem is that WebKit reacts to keydown and Opera prefers keypress, so there's kludge: both are handled and throttled.
var ignoreKey = false;
var handler = function(e)
{
if (ignoreKey)
{
e.preventDefault();
return;
}
if (e.keyCode == 38 || e.keyCode == 40)
{
var pos = this.selectionStart;
this.value = (e.keyCode == 38?1:-1)+parseInt(this.value,10);
this.selectionStart = pos; this.selectionEnd = pos;
ignoreKey = true; setTimeout(function(){ignoreKey=false},1);
e.preventDefault();
}
};
input.addEventListener('keydown',handler,false);
input.addEventListener('keypress',handler,false);
I found that a better solution is just to return false; to prevent the default arrow key behavior:
input.addEventListener("keydown", function(e) {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') return false;
}, false);
Actually, there is a better and simpler method to do this job.
$('input').bind('keydown', function(e){
if(e.keyCode == '38' || e.keyCode == '40'){
e.preventDefault();
}
});
Yes, it is so easy!
In my case (react) helped:
onKeyDown = {
(e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') e.preventDefault();
}
}
and onKeyUp was fully functional
I tested the code and it seems that it cancels the event but if you don't press the arrow for very short time - it fires keypress event and that event actually moves cursor. Just use preventDefault() also in keypress event handler and it should be fine.
Probably not. You should instead seek for a solution to move the cursor back to the end of the field where it was. The effect would be the same for the user since it is too quick to be perceived by a human.
I googled some and found this piece of code. I can't test it now and it is said to not to work on IE 6.
textBox.setSelectionRange(textBox.value.length, textBox.value.length);

Categories

Resources