Change css property depend on if condition with right key press - javascript

I'd like to change css property depend on if-condition, what mean if the user press right key change background with specific color and if he press again change background color to other color.
$(document).ready(function() {
$(document).keyup(function(e) {
var counter = 0;
switch (e.which) {
case 39: // right
if (counter == 1) {
$(".my-div").css("background-color", "red");
counter = counter + 1;
}
if (counter == 2) {
$(".my-div").css("background-color", "yellow");
counter = counter + 1;
}
if (counter == 3) {
$(".my-div").css("background-color", "green")
counter = counter + 1;
}
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
console.log(counter);
})
.my-div {
width: 1170px;
height: 500px;
margin: 50px auto;
background-color: #0026ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-div"></div>

Use the stylesheet for background color changes. Here's how you can use the element to keep track of its current state while controlling styling at the same time:
$(document).ready(function() {
$(document).keyup(function(e) {
var counter = $(".my-div").attr('rcount') || 0;
//Resets to state0. Uncomment to stop after third trigger:
//if (counter < 3)
counter = (++counter % 4);
switch (e.which) {
case 39: // right
$(".my-div").attr("rcount", counter);
break;
default:
return;
}
e.preventDefault();
});
})
.my-div {
width: 200px;
height: 500px;
margin: 50px auto;
background-color: #0026ff;
}
.my-div[rcount='0'] { background-color: #0026ff;}
.my-div[rcount='1'] { background-color: red;}
.my-div[rcount='2'] { background-color: yellow; }
.my-div[rcount='3'] { background-color: green; }
/* Debug styles added to show current rcount value */
.my-div.debug { position:relative; }
.my-div.debug:before {
content: 'rcount ' attr( rcount );
color:white;
text-shadow:1px 1px 1px black;
position:absolute;
left:0;
top:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-div debug"></div>

Move counter out of keyup event and set it to 1, use triple equals === instead and add else to conditions so it will check the condition then move to the next one, inside those conditions increment the counter :
$(document).ready(function() {
var counter = 1;
$(document).keyup(function(e) {
switch (e.which) {
case 39: // right
if (counter === 1) {
$(".my-div").css("background-color", "red");
counter++;
}else if (counter === 2) {
$(".my-div").css("background-color", "yellow");
counter++;
}else if (counter === 3) {
$(".my-div").css("background-color", "green")
counter=1;
}
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
})
.my-div {
width: 117px;
height: 50px;
margin: 50px auto;
background-color: #0026ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-div"></div>

try this out , this will show random color when you click right arrow or left arrow
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style type="text/css">
.changeme{
width: 300px;
height: 300px;
background-color: orange;
}
</style>
<body>
<div class="changeme"></div>
</body>
<script type="text/javascript">
$("body").keydown(function(e){
if(e.keyCode == 37)//when you click the left arrow button
{
var theColor = getRandomColor();
$(".changeme").css({"background-color":theColor});
}
else if(e.keyCode == 39)//when you click right arrow button
{
var theColor = getRandomColor();
$(".changeme").css({"background-color":theColor});
}
});
//generate a random color
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</html>

Related

Circle does not move right or down following arrow keypress

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>

else if not working in KeyCode events javascript

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()
}

Button background changes when the value is 0 and the value is max (jQuery)

I'm trying to figure out how to change the background color of the button when the value is 0 and the maximum value. I have made the code as below but it still doesn't work. Can anyone help me with this problem?
when i add this code in initial conditioning, it doesn't work. When i click + value dissapear
if( sum == 0 ){
$('.btn__decrement').css('background-color', '#dadada');
}
The condition what i want:
$(document).ready(function(){
$(".base-quantity .btn").on("click", function () {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
var sum = 0;
$('.base-quantity input[type="text"]').each(function () {
sum += Number($(this).val());
});
if(sum==0){
$('.btn__decrement').css('background-color', '#dadada');
}else if ($button.hasClass('btn__increment') && sum < 10) {
var newVal = parseFloat(oldValue) + 1;
$('btn__decrement').css('background-color', 'blue');
} else if ($button.hasClass('btn__decrement')) {
// nilai tidak bisa berkurang jika dibawah 0
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
} else {
return false;
}
$button.parent().find("input").val(newVal);
});
})
.base-quantity{
background-color: rgba(239,239,239,0.3);
display: flex;
align-items: center;
}
.base-quantity input{
height: 100%;
width: 100%;
text-align: center;
border: none;
background-color: transparent;
}
.base-quantity .btn{
background-color: #cc4645 ;
color: #fff;
border-radius: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="base-quantity">
<button type="button" class="btn btn__decrement">-</button>
<input type="text" id="quantityVal" value="0" disabled>
<button type="button" class="btn btn__increment">+</button>
</div>
when i add this code in initial conditioning, it doesn't work
if( sum == 0 ){
$('btn__decrement').css('background-color', '#dadada');
}
Instead of
$('btn__decrement').css('background-color', '#dadada');
use
$('.btn__decrement').css('background-color', '#dadada');
Update
I don't know what you want to achieve but but add this snap to you code may be it will give you a hint
$(document).ready(function () {
var sum = 0;
if (sum == 0) {
$('.btn__decrement').css('background-color', '#dadada');
}
$('.btn__increment').click(function () {
var oldValue = parseFloat($("#quantityVal").val());
sum = oldValue + 1;
if (sum < 10) {
$('.btn__decrement').css('background-color', 'blue');
}
$("#quantityVal").val(sum);
});
$('.btn__decrement').click(function () {
var oldValue = parseFloat($("#quantityVal").val());
if (sum > 0) {
sum = oldValue - 1;
$('.btn__decrement').css('background-color', 'blue');
}
if (sum == 0) {
$('.btn__decrement').css('background-color', '#dadada');
}
$("#quantityVal").val(sum);
});
})
This is more of a variable hoisting issue, as you have declared var newVal in if blocks so var variable will get hoisted so you will not get an error as a variable is not defined but it will be undefined as you are initializing them in the if-else condition and on the first click, those will not get executed so the value of newVal remains undefined that is why you see blank on the click.
I have provided the fix int the below code ,by the way i am not sure what are you trying to do.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.base-quantity{
background-color: rgba(239,239,239,0.3);
display: flex;
align-items: center;
}
.base-quantity input{
height: 100%;
width: 100%;
text-align: center;
border: none;
background-color: transparent;
}
.base-quantity .btn{
background-color: #cc4645 ;
color: #fff;
border-radius: 0;
}
</style>
</head>
<body>
<div class="base-quantity">
<button type="button" class="btn btn__decrement">-</button>
<input type="text" id="quantityVal" value="0" disabled>
<button type="button" class="btn btn__increment">+</button>
</div>
<script>
$(document).ready(function(){
$('.btn__increment').css('background-color', 'blue');
$(".base-quantity .btn").on("click", function () {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
var sum = 0;
var newVal=0;
$('.base-quantity input[type="text"]').each(function () {
sum += Number($(this).val());
});
if ($button.hasClass('btn__increment') && sum < 10) {
newVal = parseFloat(oldValue) + 1;
$('.btn__decrement').css('background-color', 'blue');
} else if ($button.hasClass('btn__decrement')) {
if (oldValue > 0) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
} else {
return false;
}
if(newVal==0){
clicked=false;
$('.btn__decrement').css('background-color', '#dadada');
$('.btn__increment').css('background-color', 'blue');
}
else if(newVal>0 && newVal<=10){
$('.btn__decrement').css('background-color', 'blue');
}
if(newVal < 10){
$('.btn__increment').css('background-color', 'blue');
}
else if(newVal == 10){
$('.btn__increment').css('background-color', '#dadada');
}
$button.parent().find("input").val(newVal);
});
})
</script>
</body>
</html>

stopping setTimeout loop in my snake game?

I've created a snake game, and when the snake hit the wall or itself, it still wont stop moving. I figured out if I used the clearTimeout(), it would help. but it didn't.
Is there a way to stop the loop? or it is another issue?
jQuery(document).ready(function($) {
init();
});
var move;
function init() {
board.initBoard();
drawSnake();
food.createFood();
}
function play() {
$('.newGame').css('visibility', 'hidden');
$('.playgame').css('visibility', 'hidden');
moveSnake();
getSnakeDir();
}
function gameover() {
clearTimeout(move);
$('.newGame').css('visibility', 'visible');
}
function playGame() {
$('#gameboard').empty();
$('.newGame').hide();
init();
play();
}
var board = {
DIM: 20,
initBoard: function() {
for (var i = 0; i < board.DIM; i++) {
var row = $('<div class="row-' + i + '"></div>');
for (var j = 0; j < board.DIM; j++) {
var col = ('<div class="col-' + j + '-' + i + '"></div>');
$(row).append(col);
}
$("#gameboard").append(row);
}
}
}
var snake = {
position: ['10-10', '10-11', '10-12'],
direction: 'r',
speed: 200,
};
function drawSnake() {
$('.col-10-10').addClass('snake');
$('.col-11-10').addClass('snake');
}
function getSnakeDir() {
$(document).keydown(function(event) {
//event.preventDefault();
if (event.which == 38) {
snake.direction = 'u';
} else if (event.which == 39) {
snake.direction = 'r';
} else if (event.which == 40) {
snake.direction = 'd';
} else if (event.which == 37) {
snake.direction = 'l';
}
});
}
function moveSnake() {
var tail = snake.position.pop();
$('.col-' + tail).removeClass('snake');
var coords = snake.position[0].split('-');
var x = parseInt(coords[0]);
var y = parseInt(coords[1]);
if (snake.direction == 'r') {
x = x + 1;
} else if (snake.direction == 'd') {
y = y + 1;
} else if (snake.direction == 'l') {
x = x - 1;
} else if (snake.direction == 'u') {
y = y - 1;
}
var currentcoords = x + '-' + y;
snake.position.unshift(currentcoords);
$('.col-' + currentcoords).addClass('snake');
//when snake eats food
if (currentcoords == food.coords) {
console.log('true');
$('.col-' + food.coords).removeClass('food');
snake.position.push(tail);
food.createFood();
}
//game over
if (x < 0 || y < 0 || x > board.DIM || y > board.DIM) {
gameover();
}
//if snake touch itself
if (hitItself(snake.position) == true) {
gameover();
}
move=setTimeout(moveSnake, 200);
}
var food = {
coords: "",
createFood: function() {
var x = Math.floor(Math.random() * (board.DIM-1)) + 1;
var y = Math.floor(Math.random() * (board.DIM-1)) + 1;
var fruitCoords = x + '-' + y;
$('.col-' + fruitCoords).addClass('food');
food.coords = fruitCoords;
},
}
function hitItself(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
.buttonnewgame {
position: relative;
}
.newGame {
position: absolute;
top: 45%;
left: 25%;
padding: 15px;
font-size: 1em;
font-family: arial;
visibility: hidden;
}
.gameContainer{
width: 100%;
}
#gameboard {
background-color:#eee;
padding:3px;
}
.playgame {
position: absolute;
top: 45%;
left: 20%;
padding: 15px;
font-size: 1em;
font-family: arial;
}
/* styling the board */
div[class^='row'] {
height: 15px;
text-align: center;
}
div[class*='col']{
display: inline-block;
border: 1px solid grey;
width: 15px;
height: 15px;
}
/*display the snake*/
.snake {
background-color: blue;
z-index: 99;
}
.food {
background: red;
z-index: 99;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game">
<div class="buttonnewgame">
<input type="button" name="new game" value="new game" class="newGame" onclick="playGame()" />
<button class="playgame" onclick="play()">Play Game</button>
<div class="gameContainer">
<div id="gameboard">
<!-- snake game in here -->
</div>
</div>
</div>
</div>
There were a few problems, but here is the 'working version' (there are more bugs).
1) I renamed drawSnake to createSnake. You weren't fully reinitializing the snake when you called init(). The snakes position was not being reset in the previous drawSnake method, so it would seem like the game was not playable.
After that there were 2 more bugs.
2) You have to return after you call gameOver or the game never really ends does it? Once you clear the timeout in gameover, you immediately set another Timeout for on the last line of moveSnake() because you didn't return once the game was over. That lead to weird results that made it seem like the game was unresponsive.
3) You were using a combination of visibility none or visible and $.hide(). $.hide() uses display: none, so when you tried to show it again with the visibility style change, its still display: none so the new game button would stop appearing.
My advice to any game coder is to learn how to separate the code that handles how the game works (logic of the game, how the clock ticks, initialization of game state, etc) , and how it is displayed (the html and css). Modeling the game logic after a cleanly written system is easy to read and debug. The code becomes harder to understand and modify when the display code is mixed in with game logic. In theory, our game should work perfectly without any kind of rendering. Then we could write a renderer that produces an HTML canvas, html DOM, text in the command line, or OpenGL.
Heres an old project I never finished that should illustrate a separation between model and view.
http://tando.us/ganix/ganix.htm
jQuery(document).ready(function($) {
init();
});
var move;
function init() {
board.initBoard();
createSnake();
food.createFood();
}
function play() {
$('.newGame').hide();
$('.playgame').hide();
moveSnake();
getSnakeDir();
}
function gameover() {
clearTimeout(move);
$('.newGame').show();
}
function playGame() {
$('#gameboard').empty();
$('.newGame').hide();
init();
play();
}
var board = {
DIM: 20,
initBoard: function() {
for (var i = 0; i < board.DIM; i++) {
var row = $('<div class="row-' + i + '"></div>');
for (var j = 0; j < board.DIM; j++) {
var col = ('<div class="col-' + j + '-' + i + '"></div>');
$(row).append(col);
}
$("#gameboard").append(row);
}
}
}
var snake = {
position: ['10-10', '10-11', '10-12'],
direction: 'r',
speed: 200,
};
function createSnake() {
$('.col-10-10').addClass('snake');
$('.col-11-10').addClass('snake');
snake.position = ['10-10', '10-11', '10-12'];
}
function getSnakeDir() {
$(document).keydown(function(event) {
//event.preventDefault();
if (event.which == 38) {
snake.direction = 'u';
} else if (event.which == 39) {
snake.direction = 'r';
} else if (event.which == 40) {
snake.direction = 'd';
} else if (event.which == 37) {
snake.direction = 'l';
}
});
}
function moveSnake() {
var tail = snake.position.pop();
$('.col-' + tail).removeClass('snake');
var coords = snake.position[0].split('-');
var x = parseInt(coords[0]);
var y = parseInt(coords[1]);
if (snake.direction == 'r') {
x = x + 1;
} else if (snake.direction == 'd') {
y = y + 1;
} else if (snake.direction == 'l') {
x = x - 1;
} else if (snake.direction == 'u') {
y = y - 1;
}
var currentcoords = x + '-' + y;
snake.position.unshift(currentcoords);
$('.col-' + currentcoords).addClass('snake');
//when snake eats food
if (currentcoords == food.coords) {
console.log('true');
$('.col-' + food.coords).removeClass('food');
snake.position.push(tail);
food.createFood();
}
//game over
if (x < 0 || y < 0 || x > board.DIM || y > board.DIM) {
gameover();
return;
}
//if snake touch itself
if (hitItself(snake.position) == true) {
gameover();
return;
}
move=setTimeout(moveSnake, 200);
}
var food = {
coords: "",
createFood: function() {
var x = Math.floor(Math.random() * (board.DIM-1)) + 1;
var y = Math.floor(Math.random() * (board.DIM-1)) + 1;
var fruitCoords = x + '-' + y;
$('.col-' + fruitCoords).addClass('food');
food.coords = fruitCoords;
},
}
function hitItself(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
.buttonnewgame {
position: relative;
}
.newGame {
position: absolute;
top: 45%;
left: 25%;
padding: 15px;
font-size: 1em;
font-family: arial;
}
.gameContainer{
width: 100%;
}
#gameboard {
background-color:#eee;
padding:3px;
}
.playgame {
position: absolute;
top: 45%;
left: 20%;
padding: 15px;
font-size: 1em;
font-family: arial;
}
/* styling the board */
div[class^='row'] {
height: 15px;
text-align: center;
}
div[class*='col']{
display: inline-block;
border: 1px solid grey;
width: 15px;
height: 15px;
}
/*display the snake*/
.snake {
background-color: blue;
z-index: 99;
}
.food {
background: red;
z-index: 99;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game">
<div class="buttonnewgame">
<input type="button" name="new game" value="new game" class="newGame" style="display:none;" onclick="playGame()" />
<button class="playgame" onclick="play()">Play Game</button>
<div class="gameContainer">
<div id="gameboard">
<!-- snake game in here -->
</div>
</div>
</div>
You could try not to initiate a new setTimeout call at the and of the moveSnake function, but instead using.
function play() {
$('.newGame').css('visibility', 'hidden');
$('.playgame').css('visibility', 'hidden');
move = setInterval(moveSnake, 200);
getSnakeDir();
}
and remove the
move = setTimeout(moveSnake, 200)
from the moveSnake function and do
function gameover() {
clearInterval(move);
$('.newGame').css('visibility', 'visible');
}

Using keyup to change absolute position using JavaScript

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>

Categories

Resources