I want my code to do the following:
when the right arrow key is pressed, move the circle to the right
when the down arrow key is pressed, move the circle to the bottom
But instead it does the following:
When one of these keys is pressed, it moves only once and than no more. What am I doing wrong?
document.onkeydown = function(event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
circle.style.left += 100;
console.log("right")
} else if (event.keyCode == 40) {
circle.style.top += 100;
console.log("bottom")
}
}
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
<div id="circle"></div>
You forgot about the units!
I changed your snippet to keep the actual values in 2 variables and added a function to update the circles style properties by using those vars and appending the units.
<html>
<head>
<title>HTML Test</title>
<style>
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="circle"></div>
</body>
<script>
var circle = document.getElementById("circle");
var circleLeft = 0;
var circleTop = 0;
var updatePosition = function(left, top) {
circle.style.left = left + 'px';
circle.style.top = top + 'px';
};
// once at the start
updatePosition(circleLeft, circleTop);
document.onkeydown = function (event) {
if (event.keyCode == 39) {
circleLeft += 100;
console.log("right");
} else if (event.keyCode == 40) {
circleTop += 100;
console.log("bottom");
}
updatePosition(circleLeft, circleTop);
}
</script>
</html>
There is probably a more elegant way of doing this, but as
Rene said in the comments, you are dealing with strings not numbers and therefore will have trouble actually preforming simple operations like += 100. You instead need to substring the style string, parse the number from it and then add your number, then re-add the "px" to the end (actually might not be necessary since it seems to infer that 100 == 100px in HTML, but not the other way around.)
Here is a fix that worked for moving it left!
<script>
circle.style.left = "0px";
document.onkeydown = function (event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
console.log(circle.style.left.substring(0,circle.style.left.length -2))
circle.style.left = (parseInt(circle.style.left.substring(0,circle.style.left.length -2)) + 100) + "px"
console.log(circle.style.left)
} else if (event.keyCode == 40) {
circle.style.top += 100;
console.log("bottom")
}
}
</script>
Here is the working example. I have set the 10px move position instead of 100px.
Here you can move the circle infinite times as well instead of the single move.
document.onkeydown = function (event) {
var circle = document.getElementById("circle");
if (event.keyCode == 39) {
for (let i = 0; i < 10; i++) {
(i => {
setTimeout(() => {
const left = window.getComputedStyle(circle).left;
circle.style.left = `${(+left.replace("px", "") + i * 2) %
window.innerWidth}px`;
}, 500);
})(i);
}
} else if (event.keyCode == 40) {
for (let j = 0; j < 10; j++) {
(i => {
setTimeout(() => {
const top = window.getComputedStyle(circle).top;
circle.style.top = `${(+top.replace("px", "") + j * 2) %
window.innerWidth}px`;
}, 500);
})(j);
}
}
}
#circle {
width: 50px;
height: 50px;
border-radius: 25px;
background: red;
position: absolute;
}
<div id="circle"></div>
Related
I am trying to make me character moving left and up and I think jump() and slideLeft()
functions are working properly and the problem is in the controller(e) function (else if (e.KeyCode===37)) . The first function is avaible but it isn't able to acces the second conditon function. Also, I would want to make the grid solid after I will make an slideRight() similar function ,so if my character is jumping on it, the platform would sustain the square . Has anyone any ideea for either of my questions ?
Code snippet:
var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;
function jump() {
if (isJumping) return
let timerUpId = setInterval(function() {
if (bottom > 250) {
clearInterval(timerUpId);
let timerDownId = setInterval(function() {
if (bottom < 0) {
clearInterval(timerDownId);
isJumping = false;
}
bottom -= 5;
square.style.bottom = bottom + 'px';
}, 20)
}
isJumping = true;
bottom += 30;
square.style.bottom = bottom + 'px';
}, 20)
}
function slideLeft() {
console.log('da');
isGoingLeft = true;
leftTimerId = setInterval(function() {
left -= 5;
square.style.left = left + 'px';
}, 20)
}
function controller(e) {
if (e.keyCode === 32)
jump();
else if (e.KeyCode === 37)
slideLeft();
}
document.addEventListener('keydown', controller);
.grid {
position: absolute;
background-color: chartreuse;
height: 20px;
width: 500px;
bottom: 100px;
left: 100px;
}
.square {
position: absolute;
background-color: darkblue;
height: 100px;
width: 100px;
bottom: 0px;
left: 150px;
}
`
<div class="grid"></div>
<div class="square"></div>
EDIT:
There is a typo:
The second time you've written KeyCode
function controller(e) {
if(e.keyCode===32) {
jump();
}
else if(e.keyCode===37) {
slideLeft();
}
}
I don't really understand what you mean by the second part of your question. If you want a character to have the ability to jump on a square, you'll have to implement a collision detection. Something like this:
if ( isNotOnGround() ) {
fall()
}
I am making a simple game using JS. In that I have to move the character left when we click on the A button in the keyboard. I got the Keycode and I am able to change the left property also, but only once. I saw many similar questions, but none of those answers helped.
Here's my code:-
HTML FILE:
<!-- The div that I wanna move -->
<div class="char-div">
<img src="game imgs/char-1.png" alt="" id="char-img">
</div>
CSS FILE:
.char-div{
/* styling of that div */
position: absolute;
/* top: 0; */
left: 350px;
bottom: 0;
}
JS FILE:
let char_div = document.getElementsByClassName('char-div')[0];
var char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
document.onkeydown = function(e){
if(e.keyCode == 65){
char_div.style.left = char_div_left - 20 + "px";
console.log(char_div_left)
}
if(e.keyCode == 68){
char_div.style.left = char_div_left + 120 +"px";
console.log(char_div_left)
}
}
You need to calculate left style of char_div in each key down event
let char_div = document.getElementsByClassName('char-div')[0];
document.onkeydown = function (e) {
var char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
if (e.keyCode == 65) {
char_div.style.left = char_div_left - 20 + "px";
// console.log(char_div_left)
}
if (e.keyCode == 68) {
char_div.style.left = char_div_left + 120 + "px";
// console.log(char_div_left)
}
}
.char-div {
/* styling of that div */
position: absolute;
/* top: 0; */
left: 350px;
bottom: 0;
}
<div class="char-div">
<img src="game imgs/char-1.png" alt="this is img" id="char-img">
</div>
You need to get these <div class="char-div"> <img src="game imgs/char-1.png" alt="" id="char-img"> </div> inside the onkeydown function
let char_div = document.getElementsByClassName('char-div')[0];
var char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
document.onkeydown = function(e) {
let char_div = document.getElementsByClassName('char-div')[0];
var char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
if (e.keyCode === 65) {
char_div.style.left = char_div_left - 5 + "px";
}
if (e.keyCode == 68) {
char_div.style.left = char_div_left + 5 + "px";
}
}
.char-div {
/* styling of that div */
position: absolute;
/* top: 0; */
left: 350px;
bottom: 0;
border: 1px solid green;
}
Your variable char_div_left doesn't update it's value on click, so it holds the initial value for all of the clicks.
I advise, however, against reading the value from computed styles altogether, just create a state variable:
let char_div = document.getElementsByClassName('char-div')[0];
let how_much_left = 350;
document.onkeydown = function(e){
if(e.keyCode == 65){
how_much_left -= 20;
char_div.style.left = how_much_left + "px";
console.log(how_much_left)
}
if(e.keyCode == 68){
how_much_left += 120;
char_div.style.left = how_much_left + "px";
console.log(how_much_left)
}
}
Here is more precise solution, this will only listen to the specific events.
let char_div = document.getElementsByClassName('char-div')[0];
let char_div_left = parseInt(window.getComputedStyle(char_div, null).getPropertyValue('left'));
document.onkeydown = function (e) {
if (e.keyCode == 65 || e.keyCode == 68) {
char_div_left = ( char_div_left + ( e.keyCode == 65 ? -20 : 120 ) );
char_div.style.left = char_div_left + "px";
}
}
I'm trying to make a hidden game, where you can move one of the letters in a word around the screen. The sentence's position is relative, but the letter's position is absolute, so if it's position isn't set, it stays where it is in the sentence. But I can't seem to access that position with javascript.
window.addEventListener("keydown", hidgame, false);
var vertpos; // = don't know what to put after the variables to get the top and left position.
var horipos;
function hidgame(event) {
if (event.keyCode == "38") {
vertpos--
document.getElementById("hidgame").style.top = vertpos + "px";
}
if (event.keyCode == "40") {
vertpos++
document.getElementById("hidgame").style.top = vertpos + "px";
}
if (event.keyCode == "37") {
horipos--
document.getElementById("hidgame").style.left = horipos + "px";
}
if (event.keyCode == "39") {
horipos++
document.getElementById("hidgame").style.left = horipos + "px";
}
#subtitle {
width: 100%;
text-align: center;
}
#hidgame {
position: absolute;
color: red;
}
<div id="subtitle">Hidden G<span id="hidgame">a</span> me</div> <!--The is only there to fill the space because the span is absolute-->
To determine the position, use Element.getBoundingClientRect().
Also, consider storing your element as a variable instead of repeatedly looking it up.
window.addEventListener("keydown", hidgame, false);
var letter = document.getElementById("hidgame");
var vertpos = letter.getBoundingClientRect().top;
var horipos = letter.getBoundingClientRect().left;
function hidgame(event) {
if (event.keyCode == "38") vertpos--; //up
else if (event.keyCode == "40") vertpos++; //down
else if (event.keyCode == "37") horipos--; //left
else if (event.keyCode == "39") horipos++; //right
letter.style.top = vertpos + "px";
letter.style.left = horipos + "px";
}
#subtitle {
width: 100%;
text-align: center;
}
#hidgame {
position: absolute;
color: red;
}
<div id="subtitle">Hidden G<span id="hidgame">a</span> me</div>
<!--The is only there to fill the space because the span is absolute-->
I cannot get this to make the square move, I do not get errors, and I have no clue why. I believe the problem originates from the way the keyboard input is processed or the method it is taken in with.
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
var pos = 0;
function myMove() {
var elem = document.getElementById("animate");
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
function myEventHandler(e) {
var keyCode = e.keyCode;
if(keyCode == 37) {
pos = pos - 1
}
if(keyCode = 39) {
pos = pos + 1
}
}
</script>
</body>
</html>
</body>
</html>
You have not added onkeydown event listener and you haven't called function to update position of element and really don't need setInterval function to do that.
var pos = 100;
function myMove() {
var elem = document.getElementById("animate");
if (pos == 350) {
clearInterval(id);
}
else {
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
function myEventHandler(e){
var keyCode = e.keyCode;
if(keyCode == 37){
pos = pos - 1;
myMove();
}
if(keyCode = 39){
pos = pos + 1;
myMove();
}
}
document.onkeydown = myEventHandler;
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<div id ="container">
<div id ="animate"></div>
</div>
You need to make sure you call your routines to initialise the page. So your script should be:
var pos = 0;
function myMove() {
var elem = document.getElementById("animate");
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
}
else {
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
function myEventHandler(e){
var keyCode = e.keyCode;
if(keyCode == 37){
pos = pos - 1
}
if(keyCode = 39){
pos = pos + 1}
}
// added these initialisation calls
myMove();
document.onkeyup = myEventHandler;
All I'm trying to do is to simply move a div around the screen using my arrow keys. I am completely newbie to JavaScript and what I wrote seems like it should be working but it's not. Every keyUp is moving the div based on it's original position and not the current position of the div. Is there something I'm missing?
CSS:
#pawn {
position: absolute;
left: 0;
top: 0;
width: 50px;
height: 50px;
}
JavaScript
function showKeyCode(e) {
var pawn = document.getElementById("pawn");
if(e.keyCode == "37") {
console.log("left");
pawn.style.left = -50+"px";
}
if(e.keyCode == "38") {
console.log("up");
pawn.style.top = -50+"px";
}
if(e.keyCode == "39") {
console.log("right");
pawn.style.left = +50+"px";
}
if(e.keyCode == "40") {
console.log("down");
pawn.style.top = +50+"px";
}
}
HTML:
<body onKeyUp="showKeyCode(event);">
<div id="pawn"></div>
</body>
Can anyone shine some light on this? I've been stuck for hours.
The pawn.style.left properties are text, so you're not actually incrementing the value at all. Essentially the assignments say "set it to positive/negative 50+"px"; every time.
You'll need to convert the values to integers and then add the new value, and then set it as the px value.
A very basic demo in jQuery:
$(function(){
$('body').on('keyup', function(e){
var pawn = $('#pawn');
var newLeft = parseInt(pawn.css('left')) + 50;
pawn.css('left',newLeft+'px');
});
});
Codepen
You can infer how to add support for the different directions/arrow keys.
You need to increment the position value but also take in count that the value you save is a string so you need to convert that back to a number so you can increment it again.
var pawn = document.getElementById("pawn");
var move = 50;
document.body.addEventListener('keyup', showKeyCode);
function showKeyCode(e) {
var num = 0;
if(e.keyCode === 37) {
num = parseInt(pawn.style.left, 10) || 0;
num -= move;
pawn.style.left = num + "px";
}
if(e.keyCode === 38) {
num = parseInt(pawn.style.top, 10) || 0;
num -= move;
pawn.style.top = num + "px";
}
if(e.keyCode === 39) {
num = parseInt(pawn.style.left, 10) || 0;
num += move;
pawn.style.left = num + "px";
}
if(e.keyCode === 40) {
num = parseInt(pawn.style.top, 10) || 0;
num += move;
pawn.style.top = num + "px";
}
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
font-family: "Trebuchet MS", sans-serif;
background-color: #ECEFF1;
}
#pawn {
background-color: #B0BEC5;
color: white;
width: 100px;
display: block;
text-align: center;
padding: 20px;
position: absolute;
left: 0;
top: 0;
}
<div id="pawn">pawn</div>