I am trying to run a function when user clicks on an rectangle by using eventlistener. So far
I only managed to run the function by using onkeydown. The eventListener doesnt work for me.
The script tag is place in the body.
<script>
var teleso = document.getElementById("teleso")
teleso.addEventListener("click", anim);
// document.onkeydown = anim;
var telesoVlevo = 0;
function anim(e) {
if (e.keyCode == 37) {
telesoVlevo -= 2;
teleso.style.left = telesoVlevo + "px";
if (telesoVlevo <= 0) {
telesoVlevo += 2;
}
}
}
</script>
Even though the question isn't very clear, I think the problem is that you are trying to look for a keycode, while if you try and add:
function anim(e) {
console.log(e.keyCode);
}
you'll get undefiend, and that's your problem (click event does not return an e.keyCode value)
so you can actually add to the condition:
function anim(e) {
if (e.keyCode == 37 || e.keyCode === 'undefined') {
telesoVlevo -= 2;
teleso.style.left = telesoVlevo + "px";
if (telesoVlevo <= 0) {
telesoVlevo += 2;
}
}
}
of course that's assuming the CSS positioning is properly set: a wrapper that is set to position: realative and the element you're trying to animate, with position: absolute.
Related
I am having a problem when I move my key controls mainly the arrows on the keyboard. If the viewpoint is small enough it also moves the screen up and down because of the vertical side bar and the tetris piece at the same time. And I want the pieces to only move when I press the arrows. I am a novice at Js and I am not sure where to start to solve the problem, suggestions to where to start to look at?
Here is my Js script
document.addEventListener("keydown", CONTROL);
function CONTROL(event) {
if (event.keyCode == 37) {
p.moveLeft();
dropStart = Date.now();
}
else if (event.keyCode == 38) {
p.rotate();
}
else if (event.keyCode == 39) {
p.moveRight();
dropStart = Date.now();
}
else if (event.keyCode == 40) {
p.moveDown(0);
}
}
Arrow keys moving the browser window is a default browser behavior.
Use event.preventDefault()
To listen only to arrow keys use if (k >= 37 && k <= 40) {, or the opposite: if (k < 37 || k > 40) return;
const p = { // JUST FOR THIS DEMO. You use Piece.prototype
moveLeft() { console.log("LEFT"); },
rotate() { console.log("ROTATE"); },
moveRight() { console.log("RIGHT"); },
moveDown() { console.log("DOWN"); },
};
document.addEventListener("keydown", CONTROL);
function CONTROL(event) {
const k = event.keyCode;
if (k < 37 || k > 40) return; // Do nothing if was not an arrow key. Else Do:
event.preventDefault(); // Prevent browser scroll on arrows
if(k == 37 || k == 39) dropStart = Date.now(); // Only for left or right
return {
37: p.moveLeft,
38: p.rotate,
39: p.moveRight,
40: p.moveDown
}[k]();
}
html, body {min-height: 100%;}
so the problem here is that is that it's sensing each key individually (I've had the same problem so you need a keymap to keep track off ALL the keys pressed like so:
var keys = [];
function keysPressed(e) {
keys[e.keyCode] = true;
}
function keysReleased(e) {
keys[e.keyCode] = false;
}
if(keys[37] === true){
//do stuff here
}
if(keys[38] === true){
//do stuff here
}
You may also want to use the proper identifier "==="
I know you have to invert the properties and I've done that. I also replaced the style.right.replace function with style.left.replace and changed the other parts to move the left property ${left + 1} and it worked! This confirms there is no typo. style.right just doesn't work at all for me. Any thoughts on this code?
//This Works!
var dodger = document.getElementById('dodger')
function moveDodgerLeft() {
var leftNumbers = dodger.style.left.replace('px', " ")
var left = parseInt(leftNumbers, 10)
if (left > 0) {
dodger.style.left = `${left - 1}px`
}
}
document.addEventListener('keydown', function(e) {
if (e.which === 37) {
moveDodgerLeft()
}
})
// This doesn't work
function moveDodgerRight() {
var rightNumbers = dodger.style.right.replace('px', " ")
var right = parseInt(rightNumbers, 10)
if (right > 0) {
dodger.style.right =`${right - 1}px`
}
}
document.addEventListener('keydown', function(e) {
if (e.which === 39) {
moveDodgerRight()
}
})
I'm making a game in which a player character moves left and right.
Since simply using an onKeyDown eventListener had my character move in a choppy fashion, and with a slight delay, I tried using requestAnimationFrame to call the movement function as often as possible, as suggested by another answer(How can I move my JS objects smoothly using keyboard input?)
however, that has changed nothing.
Here is my Javascript Code
var NodoCampo = document.getElementById("campo");
var NodoGiocatore = null;
var Left = false;
var Right = false;
var FRAMERATE = 20;
//cache giocatore
var LARG_GIOCATORE = 30;
var ALT_GIOCATORE = 30;
var X_GIOCATORE = 300;
var Y_GIOCATORE = 1100;
var VEL_GIOCATORE = 10;
function mostra_giocatore() {
if (NodoGiocatore === null) {
NodoGiocatore = document.createElement('div');
NodoGiocatore.setAttribute ('id', 'player');
NodoCampo.appendChild (NodoGiocatore);
}
NodoGiocatore.style.marginLeft = (X_GIOCATORE - LARG_GIOCATORE) + 'px';
NodoGiocatore.style.marginTop = (Y_GIOCATORE - ALT_GIOCATORE) + 'px';
}
function muovi() {
if (Left) {
X_GIOCATORE = X_GIOCATORE - VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
else if (Right) {
X_GIOCATORE = X_GIOCATORE + VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
}
function stop() {
Left = false;
Right = false;
}
function interfaccia(e) {
//freccia sinstra
if (e.keyCode === 37) {
X_GIOCATORE = X_GIOCATORE - VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
//freccia destra
else if (e.keyCode === 39) {
X_GIOCATORE = X_GIOCATORE + VEL_GIOCATORE;
//aggiorno immagine
mostra_giocatore();
}
}
function inizia() {
mostra_giocatore();
requestAnimationFrame(muovi);
}
window.document.onkeypress = interfaccia;
window.document.onkeyup = stop;
Your choppy movement is likely a result of the amount you are moving the player on each frame with VEL_GIOCATORE. Try reducing this amount to observe smoother movement.
The delay you are experiencing is likely due to your operating system or browsers individual settings on how key presses should repeat. You can work around this by implementing your own key tracking -- it looks like you've started to experiment with this. Track the state of your left and right keys by updating a boolean value in onkeydown and onkeyup event listeners.
var keys = {
left: false,
right: false
};
window.document.onkeydown = function (e) {
if (e.keyCode === 37) {
keys.left = true;
} else if (e.keyCode === 39) {
keys.right = true;
}
window.document.onkeyup = function (e) {
if (e.keyCode === 37) {
keys.left = false;
} else if (e.keyCode === 39) {
keys.right = false;
}
Then, in your muovi function, check the state of these variables to determine if you should update the position of the player.
When I hit the right arrow, it does not change the variable. Here's my code:
var squareX = 10;
document.addEventListener("keypress", function(e) {
if (e.keyCode === 39) {
squareX += 10;
}
});
Use keydown instead of keypress:
document.addEventListener("keydown", function(e) {
if (e.keyCode === 39) {
squareX += 10;
}
});
That did the trick for me!
I feel like a complete klutz, I had this working and then I accidentally forgot to save it! I'm an idiot. I've spent the last day trying to recreate what I had but I can't do it. Basically (from my last save) I had this:
function canvasMove(e) {
if(!e) var e = window.event;
var downcheck;
var upcheck;
var leftcheck;
var rightcheck;
if(e.keyCode == '38') {
if(up + down == 0) downcheck = false;
else downcheck = true;
e.preventDefault();
}
if(e.keyCode == '40') {
if(up + down > HEIGHT - 110) upcheck = false;
else upcheck = true;
e.preventDefault();
}
if(e.keyCode == '37') {
if(left + right == 0) rightcheck = false;
else rightcheck = true;
e.preventDefault();
}
if(e.keyCode == "39") {
if(left + right > WIDTH - 110) leftcheck = false;
else leftcheck = true;
e.preventDefault();
}
if(leftcheck == true) { left += 10; counting() };
if(rightcheck == true) { right -= 10; counting() };
if(upcheck == true) { up += 10; counting(true) };
if(downcheck == true) { down -= 10; counting(true) };
}
The problem of course being that Javascrpt doesn't support the ability to check if two keys are being pressed at the same time. What I want to accomplish is when the user pressed up and left they'll move diagonally. Ignore the "counting" function, it's just to keep track of how much the user has moved.
I managed to accomplish this with just else and if statements, no less! So I was wondering if you guys could give it a shot. The first if statement in each key if statement is so the user can't leave the canvas box. Then I have a function that moves the user by redrawing the canvas.
function redraw() {
clear(draw);
draw.fillStyle = 'rgba(0,0,0,0.5)';
draw.fillRect(left + right, up + down, '100', '100');
}
The "clear" function is just a simple function that clears the entire canvas. This is all controlled by an init function that looks like this:
function init() {
canvas = document.getElementById('game');
HEIGHT = canvas.height;
WIDTH = canvas.width;
draw = canvas.getContext('2d');
setInterval(redraw, 30);
document.onkeydown = canvasMove;
}
Your -check flags need to be global variables rather than function-scoped variables, otherwise they will never stay set between keydown events (handling only one key at a time). You also need a keyup event handler that will unset the correct flag when a key is released.