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
Related
I noticed that these function doesn't work good in Firefox, but does in Chrome.
I use these function in a game in Js to shoot bullet (left mouse click) and to create a fireball all around the player with the right click that burns everyone in a small radius.
document.onclick = function(event) {
if(!player){ //to avoid onclick to be used before calling Player();
return;
}
if(player.canAttack && player.distance >= 80) { //not for sword attack
performAttack(player);
player.canAttack = false;
}
if(player.distance < 80)
performAttack(player);
//event.preventDefault();
}
document.oncontextmenu = function(event) {
//hide default behaviour of right click -> no context menu popup
event.preventDefault();
if(player.obtainedGadjet > 0) {
player.pressingMouseRight = true;
performSpecialAttack(player);
}
}
In the performAttack function I set player.isStopped = true, so my updatePlayer() doesn't change player.x and player.y while he's attacking. The same for the fireball attack. I want my player stays there.
It works in chrome, my player stops, attacks,and then can moves again, but in Firefox if I right click it somethimes acts instead as I have left clicked, so shoot the magic ball, and maybe then the fireball too. Furthermore, my player ignore isStopped = true, it seems like in Firefox oncontextmenu has "lower priority" than other events.
Any idea?
Thanks
Please note that a click event contains information about which button was pressed. You can try yourself with something like:
document.addEventListener('click', function(ev){
console.log(ev.button);
});
And, yes, click events are fired when you right-click, even if you're doing something on related contextmenu events.
So your code should look a bit more like
document.addEventListener('click', function(ev){
if (ev.button === 0) {
// Perform primary action
} else if (ev.button === 2) {
// Perform secondary action
}
});
document.addEventListener('contextmenu', function(ev){
ev.preventDefault();
});
Using the same click event is advisable as said by Ivan. You may also want to read this other discussion here on SO about best practices and why it's not always good to disable default right click behaviour (i.e.: it's not always guaranteed to work).
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 am a beginner coder in my high school programming class, I am currently trying to edit a HTML/Javascript game I found online and I would like to update a function called acceleration:
function accelerate(n) {
myGamePiece.gravity = n;
}
with a keypress or keydown/up event. What it would do is make a box accelerate up or down whether the spacebar is pressed. The issue is the only good event listener examples I can find use buttons, and the game currently works using an acceleration button:
<button onClick="" onkeydown="accelerate(-.5)" onkeyup="accelerate(.5)">Start Game</button>
The issue is that I want the window / document (I don't know which it is) to detect if the user is inputting the spacebar key and to update the acceleration function accordingly.
I would very much appreciate any help anyone would be willing to give, thank you :D
You can (and should) use addEventListener. It's a better way of setting up event handlers since it isn't mixed in with your HTML, can be done on dynamic elements and allows multiple handlers for a single event.
document.addEventListener('keydown', function(e) {
// Prevent space from causing the page to scroll
e.preventDefault();
// A nice tool for finding key codes: http://keycode.info/
var isPressingSpace = (e.keyCode === 32);
var isPressingA = (e.keyCode === 65); // Can also use A, if you want
if (isPressingSpace || isPressingA) {
document.querySelector('span').innerText = 'Accelerating';
}
});
document.addEventListener('keyup', function() {
document.querySelector('span').innerText = 'Decelerating';
});
<span>Decelerating</span>
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)
I am programming a jQuery plugin which tracks specific events. I have provided 2 JSFiddle examples for the sanitised code to assist at the end of the question.
I am struggling to fathom why 2 particular events are not firing. The first function tracks when the user triggers the backspace or delete keys within an input or textarea field. The code for this:
// Keydown events
$this.keydown(function (e) {
var keyCode = e.keyCode || e.which;
// Tab key
if (e.keyCode === 9) {
alert('tab key');
} else if (e.keyCode === 8 || e.keyCode === 46) { // Backspace and Delete keys
if ($this.val() !== '') {
alert('Backspace or delete key');
}
}
});
I only wish to track the error-correction keys when a field is not empty. The tab key in the above example works as expected within the conditional statement. The backspace and delete keys do not work when inside the plugin and targeting the element in focus.
The second event not firing is tracking whether a user becomes idle. It is making use of jQuery idle timer plugin to manipulate the element in focus.
// Idle event
$this.focus(function() {
$this.idleTimer(3000).bind('idle.idleTimer', function() {
alert('Gone idle');
});
}).focusout(function() {
$this.idleTimer('destroy');
});
With both of these events I have refactored the code. They were outside of the plugin and targeted $('input, select, textarea') and worked as expected. I have brought them inside the plugin, and set them to $(this) to manipulate elements currently in focus. For most of the functions, this has worked without fault, but these 2 are proving problematic.
The first JSFiddle is with the 2 functions inside the plugin. tab works, whereas the correction keys do not. Strangely, in this example the idle function is firing (it does not in my dev environment). As this is working in the JSFiddle, I accept this may be difficult to resolve. Perhaps suggestions on handling an external plugin within my own to remedy this?
Fiddle 1
The second JSFiddle has taken the backspace and delete key functionality outside of the plugin and targets $('input, select, textarea') and now works.
Fiddle 2
For Fiddle1:
if ($this.val() !== '') {
alert('Backspace or delete key');
}
Look at what $this actually is.