I have a game captured inside of an Iframe within my body. Problem is, the entire page scrolls when the arrow keys are pressed. How can I prevent this? I don't want to disable scrolling with the arrow keys alogether, only when the game is being played.
Use a variable as a flag and add an event listener to see if that flag is present, if so, disable the key: Live demo here (click).
var flag = true;
document.body.addEventListener('keydown', function(e) {
var badKey = 40; //down array keyCode
if (flag && e.keyCode === badKey) {
e.preventDefault();
}
});
You can apply a key listener and stop the normal functioning of specific inputs based on conditions (like while playing a game)
Related
Just started learning HTML/css/javascript within the last 4 days.
I'm having an issue with my page. Right now I have the onlick function on my page on previous user button.
How can I change from onclick button to onkeypress?
Hoping the page can slide on a specific key command instead of a click.
<script>
function openNav() {
document.getElementById("users").style.width = "100%";
}
function closeNav() {
document.getElementById("users").style.width = "0%";
}
</script>
<div id="users" class="loggedusers">
×
<div class="overlay-content">
Previous logged Users
<div id="previoususer">
<span style="font-size:35px;cursor:pointer;" onclick="openNav()">⇒ Previous Users</span>
</div>
You can use the keypress event for this: https://developer.mozilla.org/en-US/docs/Web/Events/keypress
E.g:
const input = document.querySelector('input');
const log = document.getElementById('log');
input.addEventListener('keypress', logKey);
function logKey(e) {
log.textContent += ` ${e.code}`;
if(e.code == 'ArrowLeft') {
//Slide to the left
}
if(e.code == 'ArrowRight') {
//Slide to the right
}
}
With e.code you can query the pressed key. Examples:
ArrowUp
ArrowLeft
ArrowRight
ArrowDown
If you want your whole page to react on a keypress-event instead just a input field, you can use this:
document.onkeypress = keyPressFunction;
function keyPressFunction(e){
// here comes your keypress-code
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
console.log(charCode);
}
Just put this snippet inside your script-tag.
Like onclick there are three kinds of keyboard events. onkeydown, onkeyup and onkeypress.
onkeydownemits when user press a button (the press only)
onkeyup emits when user release the button
onkeypress emits when user press a button
You need to use keypress event on window and call the function inside if statements when user press specific key.
function openNav() {
document.getElementById("users").style.width = "100%";
}
function closeNav() {
document.getElementById("users").style.width = "0%";
}
window.addEventListener("keydown", function(e) {
if(e.keyCode === 38) {
closeNav(); // this function will be executed when user press Arrow Up key
}else if(e.keyCode === 40) {
openNav(); // this function will be executed when user press Arrow Down key
}
});
Here, window.addEventListener execute the function which is inside of it when user presses a key.
And if statements will call the closeNav() function if Arrow Up is pressed and will call openNav() function if Arrow Down is pressed.
if other keys are pressed if statements will not run.
Keyboard Events
In javascript we have three keyboard event
keydown
keypress
keyup
triggered exactly in this order.
in my opinion the best way to work with keyboard navigation is to use the "keydown" event as in the Sandesh's example.
Handling events
To handle these events you have 3 way: (examples for "keydown")
1. in markup
<element onkeydown="myScript">
2. javascript element.onkeydown
object.onkeydown = function(){myScript};
3. javascript element.addEventListener
object.addEventListener("keydown", myScript);
Due to security issue the best way is to use the third. (you can get more information googling 'XSS' or 'cross site scripting') Infact to prevent XSS in your site you need to add some http headers that block inline scripts (CSP).
furthermore you can pass true to the third parameter of addEventListener method to capture the event before being dispatched to any EventTarget beneath it in the DOM tree and then you can stop propagation if the key code matches the reserved one. It depends on the user experience that you want to implement.
Keycodes
Try this site to get keycodes: keycode.info
in my opinion, for your case the best way is to use event.code.
Resources:
MDN - keypress
MDN - addEventListener
I use Angular 6 and Leaflet 1.2 for my project.
I want to reproduce the dragging effect when a user maintain a right or left click on Leaflet Map.
For example, i want to be able to start dragging the map when I constantly pressing the space bar.
I have already test many features like calling the 'mousedown', 'mouseup', 'click', 'drag', 'dragstart' events on Leaflet Map but nothing occur ; the event is calling correctly but the dragging event does not occur.
I'm still blocking on that and the web seem not to search this functionality :o
Thanks for help !
Regards
You can easily add an event listener to detect when the space bar is held down. However you then need to have some way to tell the map which direction to move in. Assuming you want this to be done via the keyboard too, here is some example code to add/remove scrolling via the arrow keys when the space bar is held down.
function scrollMap(e) {
const key = e.key;
if (key == 'ArrowUp'){
//scroll map 100px up, or whatever you want
}
//repeat for other arrow keys, or inputs of your choice
}
document.addEventListener('keydown', (event) => {
const key = event.code;
if (key == 'Space'){
listen();
}
});
document.addEventListener('keyup', (event) => {
const key = event.code;
if (key == 'Space'){
stopListen();
}
});
function listen(){
document.addEventListener('keypress', scrollMap);
}
function stopListen(){
document.removeEventListener('keypress', scrollMap);
}
Notes
1) Depending on your page layout, it might be better to attach the events to your map element rather than the document
2) The choice of event.code vs event.key etc will depend on what browsers you are targeting. See here for more info
3) Instead of the space bar, you might want to use shift / ctrl / alt instead as these are inbuilt on the keyboard events & so are easier to detect & use cross browser. See here for more info
I am trying to make a game which has the feature that if you hold the shift key, the player will speed up. I tried to use keyEvent but it can't detect the key is held or pressed. and when I release the shift key, the player remains in speed up mode and won't change the speed back to normal. is there any possible way to achieve this?
You should listen for two events: keydown and keyup. In every event type you should check for key (the keycode of "shift" is 16), and on keydown you should start an action, and on keyup stop it (if event.keyCode === 16). Here is a simple example with text color, it becomes red while "shift" is pressed (don't forget to click on opened window of the snippet, it will not work without it because without focusing on this window all events will be "out of scope" for the snippet):
var onkeydown = (function (e) {
if (e.keyCode === 16) {
document.getElementById("target").style.color = "red";
}
});
var onkeyup = (function (e) {
if (e.keyCode === 16) {
document.getElementById("target").style.color = "black";
}
});
<h1 id="target">Red when holds "shift"</h1>
I am using X3DOM for a simple game, but I can't use keyboard keys the way I want to, because X3DOM reacts to them.
Example:
window.addEventListener('keydown', event => this.onKeyDown(event));
I want to have my own key event for if keyCode == 68. That works, but X3DOM reacts to it too, by changing the navigation mode and displaying an overlay.
How can I disable this?
disclaimer: I've never used x3dom, I was just poking around in the source code
there appears to be some code which disables keypress handling
this.disableKeys = x3dElem.getAttribute("keysEnabled");
this.disableKeys = this.disableKeys ? (this.disableKeys.toLowerCase() == "true") : false;
which is later read when setting up the keypress event handler:
this.onKeyPress = function (evt) {
if (!this.parent.disableKeys) {
evt.preventDefault();
this.parent.doc.onKeyPress(evt.charCode);
}
this.parent.doc.needRender = true;
}
So it appears setting keysEnabled=... attribute can turn this off. The oddity appears to be that their logic is backwards (?) for the condition:
x3dElem.getAttribute("keysEnabled") must be truthy (that is, it must have an attribute)
if that is falsey, this.disableKeys is always false
otherwise it is equal to that attribute's value lower-cased being equal to 'true'
So to disable keypress events, use <... keysEnabled="true" ...>
I made a github issue about the backwards logic, perhaps in the future it will be keysDisabled="true" instead
update:
in the latest version the attribute has been renamed to disableKeys so use <... disableKeys="true" ...>
You can use event.preventDefault to prevent X3DOM from reacting to that key:
window.addEventListener('keydown', event => {
if ((event.which === 68) || (event.keyCode === 68)){
event.preventDefault();
//
// ...
//
}
});
I see some similar questions here (like JavaScript: Check if CTRL button was pressed) but my problem is actually the event triggering. My js code:
// Listen to keyboard.
window.onkeypress = listenToTheKey;
window.onkeyup = listenToKeyUp;
/*
Gets the key pressed and send a request to the associated function
#input key
*/
function listenToTheKey(e)
{
if (editFlag == 0)
{
// If delete key is pressed calls delete
if (e.keyCode == 46)
deleteNode();
// If insert key is pressed calls add blank
if (e.keyCode == 45)
createBlank();
if (e.keyCode == 17)
ctrlFlag = 1;
}
}
The event triggers for any other keys except the ctrl.
I need to also trigger it for ctrl.
I can't use jQuery/prototype/whatever so those solutions are not acceptable.
So... how can I detect the ctrl?
Try using if (e.ctrlKey).
MDN: event.ctrlKey
Using onkeydown rather than onkeypress may help.
From http://www.w3schools.com/jsref/event_onkeypress.asp
Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL,
SHIFT, ESC) in all browsers. To detect only whether the user has
pressed a key, use the onkeydown event instead, because it works for
all keys.
Your event has a property named ctrlKey. You can check this to look if the key was pressed or not. See snippet below for more control like keys.
function detectspecialkeys(e){
var evtobj=window.event? event : e
if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
document.onkeypress=detectspecialkeys
This is basically Rick Hoving's answer, but it uses keydown like Danielle Cerisier suggests
function detectspecialkeys(e) {
var evtobj = window.event ? event : e
if (evtobj.ctrlKey)
console.log("You pressed ctrl")
}
document.onkeydown = detectspecialkeys
Please note that you may have to click inside the preview box to focus before pressing ctrl