Below is an example of a box moving left,right,up or down based
on pressing the arrow keys. However when I added a "laser" and used
the exact same principal/code to move the laser from left to right using "laserLeft++;" with the space bar, it does not move. I have very
carefully duplicated the code from the "square" to apply to the laser and
I cannot find why there is no movement. (I did not copy and paste the entire view source since it isn't relevant to problem).
the specific function is question is fireLaser().
#square {
position: absolute;
top: 0px;
left: 0px;
height: 5px;
width: 5px;
background-color: white;
}
#laser {
postion: absolute;
top: 0px;
left 0px;
height: 2px;
width: 5px;
background-color: red;
}
<script>
document.addEventListener("keydown", keyBoardInput);
var boxTop = 0;
var boxLeft = 0;
var laserTop = 0;
var laserLeft = 0;
function moveBoxUp(){
var square = document.getElementById("square");
boxTop--;
square.style.top = boxTop;
};
function moveBoxDown(){
var square = document.getElementById("square");
boxTop++;
square.style.top = boxTop;
};
function moveBoxLeft(){
var square = document.getElementById("square");
boxLeft--;
square.style.left = boxLeft;
};
function moveBoxRight(){
var square = document.getElementById("square");
boxLeft++;
square.style.left = boxLeft;
};
function fireLaser(){
var laser = document.getElementById("laser");
laserLeft++;
laser.style.left = laserLeft;
};
var i = event.keyCode;
if(i == 38){
moveBoxUp();
};
if(i == 40){
moveBoxDown();
};
if(i == 37){
moveBoxLeft();
};
if(i == 39){
moveBoxRight();
};
if (i == 32){
fireLaser();
};
};
</script>
I found my error!!! it was incorrectly typed "postion: absolute;" now it works perfectly!!!
Related
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>
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 have created a set of dots using div tags inside a div tag. My need is when I drag the last dot, the whole set of dots should move and sit where mouse pointer is placed at present. I tried achieving it using addeventlistner for mouse clicks but failed in my attempt.
Can someone point out the intuition in the segment below?
var dots = document.createElement("div");
dots.className = "dots";
document.body.appendChild(dots);
var dotarray = [];
for (index = 0; index < 10; index++) {
dotarray[index] = document.createElement("div");
dotarray[index].className = "dot";
dots.appendChild(dotarray[index]);
}
dotarray[9].addEventListener("mousedown", function(event) {
if (event.which == 1) {
var currentMousePointerPos, latestMousePointerPos;
currentMousePointerPos = event.pageX;
dotarray[9].addEventListener("mouseup", function(event) {
latestMousePointerPos = event.pageX;
if (currentMousePointerPos != latestMousePointerPos) {
dots.style.marginLeft = currentMousePointerPos + latestMousePointerPos;
}
})
}
})
.dot {
width: 8px;
height: 8px;
border-radius: 4px;
background-color: red;
display: inline-block;
margin-left: 5px;
}
.dots {
border: 1px solid black;
width: 135px;
}
The immediate answer to your question is that dots.style.marginLeft needs to be equal to a string, containing the units.
Hence, this would work:
dots.style.marginLeft = ((currentMousePointerPos+latestMousePointerPos) + "px");
However:
Your mouseup listener only listens to the event that the mouse click is released when it's over the element, so it doesn't do much. If you assign the listener to the whole document, the listener's function would be activated no matter where the mouseup event occurres.
currentMousePointerPos + latestMousePointerPos doesn't represent the final position of the mouse.
If we fix these two issues the will code still operate weirdly, because the left side of the dots element is set to the mouse's last position.
Therefore we just need to subtract the element's width from the marginLeft property.
The following code combines everything I've mentioned:
var dots = document.createElement("div");
dots.className = "dots";
document.body.appendChild(dots);
var dotarray = [];
for (index = 0; index < 10; index++) {
dotarray[index] = document.createElement("div");
dotarray[index].className = "dot";
dots.appendChild(dotarray[index]);
}
dotarray[9].addEventListener("mousedown", function(event) {
if (event.which == 1) {
var currentMousePointerPos;
// Notice how the listener is bound to the whole document
document.addEventListener("mouseup", function(event) {
currentMousePointerPos = event.pageX;
dots.style.marginLeft = ((currentMousePointerPos-dots.offsetWidth) + "px");
})
}
})
.dot {
width: 8px;
height: 8px;
border-radius: 4px;
background-color: red;
display: inline-block;
margin-left: 5px;
}
.dots {
border: 1px solid black;
width: 135px;
}
Is this what you are looking for?
You should use the mousemove event instead to detect any dragging
after mousedown.
var dots = document.createElement("div");
dots.className = "dots";
document.body.appendChild(dots);
var dotarray = [];
for (index = 0; index < 10; index++) {
dotarray[index] = document.createElement("div");
dotarray[index].className = "dot";
dots.appendChild(dotarray[index]);
}
dotarray[9].addEventListener("mousedown", function(event) {
if (event.which == 1) {
window.addEventListener('mousemove', move, true);
/*var currentMousePointerPos, latestMousePointerPos;
currentMousePointerPos = event.pageX;
dotarray[9].addEventListener("mouseup", function(event) {
latestMousePointerPos = event.pageX;
if (currentMousePointerPos != latestMousePointerPos) {
dots.style.marginLeft = currentMousePointerPos + latestMousePointerPos;
}
})*/
}
});
window.addEventListener("mouseup", function(event) {
window.removeEventListener('mousemove', move, true);
});
function move(e){
var div = document.getElementsByClassName('dots')[0];
div.style.position = 'absolute';
div.style.top = -8+e.clientY + 'px';
div.style.left = -135+8+e.clientX + 'px';
}
.dot {
width: 8px;
height: 8px;
border-radius: 4px;
background-color: red;
display: inline-block;
margin-left: 5px;
}
.dots {
border: 1px solid black;
width: 135px;
}
When the right arrow key is pressed I would like to increment the left position of a div by 10px using the style property. Here is my script and what I've tried so far:
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if (k.keyCode == RightBtn) {
document.getElementById("test").style.left = document.getElementById("test").style.left + 10px;
}
}
#test {
position: relative;
left: 0px;
width: 25px;
height: 80px;
background-color: black;
}
<div id="test"></div>
The style property of a DOM element is essentially a dictionary with string key-value pairs. It expects a CSS key, and a proper string value.
Your current code comes out as left: 10px10px and that doesn't make much sense for CSS.
In order for this to work, you'd have to regard the px.
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if (k.keyCode == RightBtn) {
var moveEl = document.getElementById("test"),
currLeft = parseInt(moveEl.style.left || 0);
moveEl.style.left = (currLeft + 10) + 'px';
}
}
#test {
position: relative;
left: 0px;
width: 25px;
height: 80px;
background-color: black;
}
<div id="test"></div>
Further reading and examples - HTMLElement.style
Remove px from 10.
if (k.keyCode == RightBtn) {
document.getElementById("test").style.left = document.getElementById("test").style.left + 10;
}
Try following way:
document.onkeydown = KeyPressed;
function KeyPressed(k) {
var LeftBtn = 37;
var RightBtn = 39;
var UpBtn = 38;
var DownBtn = 40;
if(k.keyCode == RightBtn) {
document.getElementById("test").style.left = parseInt(document.getElementById("test").style.left || 0) + 10 + 'px';
}
}
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>