Document is not defined error for 'document.getElementById()' - javascript

Essentially, I keep getting the message "document is not defined" when I run my .js doc on command line. I'm trying to create a super basic game where the user helps the squirrel get to the chestnuts by using arrow keys. So far I can't move the squirrel yet, and I suspect it has to do with the document is not defined error that I'm getting (lines 1-3 and maybe also 52 in the link).
You can find my code (html, css and js) in the following jsfiddle link
(http://jsfiddle.net/8Lbkcsq2/)
var squirrelImg = document.getElementById("squirrelImg");
var forest = document.getElementById("forest");
var chestnutImg = document.getElementById("chestnutsImg");
var squirrel = {
name: "Mr. Squirrel",
has_chestnuts: false,
hungry: true
};
var chestnuts = {
name: "chestnuts"
};
var positionLeft = 0;
var positionTop = 0;
function move(e) {
// 39 for right arrow
if (e.keyCode === 39) {
if (positionLeft < 850) {
positionLeft += 50;
squirrelImg.style.left = positionLeft + "px";
}
}
// 40 for down arrow
if (e.keyCode === 40) {
if (positionTop < 600) {
positionTop += 50;
squirrelImg.style.top = positionTop + "px";
}
}
// 37 for left arrow
if (e.keyCode === 37) {
positionLeft -= 50;
if (positionLeft < 0) {
positionLeft += 50; // CHANGE TO +=50 LATER
}
squirrelImg.style.left = positionLeft + "px";
}
// 38 for up arrow
if (e.keyCode === 38) {
positionTop -= 100;
if (positionTop < 0) {
positionTop += 50; // CHANGE TO +=50 LATER
}
squirrelImg.style.top = positionTop + "px";
}
foundChestnuts();
}
document.onKeyDown = move();
function foundChestnuts() {
if ((squirrelImg.style.top == "300px") && (squirrelImg.style.left == "750px")) {
squirrel.has_chestnuts = true;
alert("Thank you for helping Mr. Squirrel find his chestnuts!");
var eat = confirm("Should Mr.Squirrel eat his chestnuts?");
if (eat === true) {
alert("Time to eat!");
alert("Yum! Mr. Squirrel isn't hungry anymore!");
} else {
alert("I guess Mr. Squirrel can wait a little longer...");
}
} else {
squirrel.has_chestnuts = false;
}
}
body {
background-color: #b5916c;
}
h3 {
font-weight: bold;
text-decoration: underline;
}
p {
font-family:'Dancing Script', cursive;
font-size: large;
}
#forest {
background-image: url(http://s21.postimg.org/jyht762hj/forestfloor.jpg);
width: 850px;
height: 600px;
position: relative;
/*opacity: 0.5;*/
}
#squirrelImg {
position: absolute;
background-image: url(http://s24.postimg.org/wkqh9by4x/squirrel.png);
height: 100px;
width: 100px;
left: 0;
top: 0;
}
#chestnutsImg {
position: absolute;
background-image: url(http://s28.postimg.org/kgiubxhnd/chestnuts.jpg);
height: 100px;
width: 100px;
left: 750px;
top: 300px;
}
<body>
<h3>A Plea from Mr. Squirrel:</h3>
<p>My dearest human,</p>
<p>I seem to have misplaced my chestnuts and I am quite famished.</p>
<p>Would you mind assisting me in locating them?</p>
<p>Much obliged!</p>
<div id="forest">
<div id="squirrelImg"></div>
<div id="chestnutsImg"></div>
</div>
</body>

The issue is that move() requires an event to be passed to it but when you do document.onKeyDown = move(); no event is passed.
Change document.onKeyDown = move(); to document.addEventListener("keydown", move, false);
working jsfiddle

Add a event listener document.body.addEventListener('keydown', function(e) {...} instead of document.onKeyDown = move().
Updated Fiddle
var squirrelImg = document.getElementById("squirrelImg");
var forest = document.getElementById("forest");
var chestnutImg = document.getElementById("chestnutsImg");
var squirrel = {
name: "Mr. Squirrel",
has_chestnuts: false,
hungry: true
};
var chestnuts = {
name: "chestnuts"
};
var positionLeft = 0;
var positionTop = 0;
document.body.addEventListener('keydown', function(e) {
// 39 for right arrow
if (e.keyCode === 39) {
if (positionLeft < 850) {
positionLeft += 50;
squirrelImg.style.left = positionLeft + "px";
}
}
// 40 for down arrow
if (e.keyCode === 40) {
if (positionTop < 600) {
positionTop += 50;
squirrelImg.style.top = positionTop + "px";
}
}
// 37 for left arrow
if (e.keyCode === 37) {
positionLeft -= 50;
if (positionLeft < 0) {
positionLeft += 50; // CHANGE TO +=50 LATER
}
squirrelImg.style.left = positionLeft + "px";
}
// 38 for up arrow
if (e.keyCode === 38) {
positionTop -= 100;
if (positionTop < 0) {
positionTop += 50; // CHANGE TO +=50 LATER
}
squirrelImg.style.top = positionTop + "px";
}
foundChestnuts();
});
// combined 3 functions previously separated for foundChestnuts, eatChestnuts and hungerLevel into the function below
function foundChestnuts() {
if ((squirrelImg.style.top == "300px") && (squirrelImg.style.left == "750px")) {
squirrel.has_chestnuts = true;
alert("Thank you for helping Mr. Squirrel find his chestnuts!");
var eat = confirm("Should Mr.Squirrel eat his chestnuts?");
if (eat === true) {
alert("Time to eat!");
alert("Yum! Mr. Squirrel isn't hungry anymore!");
} else {
alert("I guess Mr. Squirrel can wait a little longer...");
}
} else {
squirrel.has_chestnuts = false;
}
}
body {
background-color: #b5916c;
}
h3 {
font-weight: bold;
text-decoration: underline;
}
p {
font-family: 'Dancing Script', cursive;
font-size: large;
}
#forest {
background-image: url(http://s21.postimg.org/jyht762hj/forestfloor.jpg);
width: 850px;
height: 600px;
position: relative;
/*opacity: 0.5;*/
}
#squirrelImg {
position: absolute;
background-image: url(http://s24.postimg.org/wkqh9by4x/squirrel.png);
height: 100px;
width: 100px;
left: 0;
top: 0;
}
#chestnutsImg {
position: absolute;
background-image: url(http://s28.postimg.org/kgiubxhnd/chestnuts.jpg);
height: 100px;
width: 100px;
left: 750px;
top: 300px;
}
<body>
<h3>A Plea from Mr. Squirrel:</h3>
<p>My dearest human,</p>
<p>I seem to have misplaced my chestnuts and I am quite famished.</p>
<p>Would you mind assisting me in locating them?</p>
<p>Much obliged!</p>
<div id="forest">
<div id="squirrelImg"></div>
<div id="chestnutsImg"></div>
</div>
</body>

please place the script before </body>, or in window.onload callback function.
Because document object is not created when you call document.getElementById.
Yes, the problem is document.onKeyDown = move(). The right event handler isdocument.onkeydown, and handler should be a function move, not a function result move(). So just changed to document.onkeydown=move

Related

If my snake dies going downward or upward, it continues the upward/downward after restart. Why?

I am trying to make a snake game.
I made the movement and I added a die function so when the character hits the border, dies.
If the character dies going downward or upward, when it restart, the character continues the upward/downward movement.
When it dies going to the left or right, it restarts as it should.
HTML and Javascript:
var upDown = 0,
rightLeft = 0;
var k, move, character;
window.onload = function() {
move = setInterval(right, 10);
character = document.getElementById('character');
setInterval(die, 10);
}
document.onkeydown = function(event) {
k = event.keyCode;
}
function die() {
if (rightLeft > 1465 || rightLeft < 0 || upDown > 650 || upDown < 0) {
clearInterval(move);
upDown = 0;
rightLeft = 0;
character.style.left = 0 + "px";
character.style.top = 0 + "px";
move = setInterval(right, 10);
alert("You lost!");
}
}
function right() {
rightLeft++;
character.style.left = rightLeft + 'px';
if (k == 38) {
console.log(move);
clearInterval(move);
console.log(move);
move = setInterval(up, 10);
} else if (k == 40) {
clearInterval(move);
move = setInterval(down, 10);
}
}
function left() {
rightLeft--;
character.style.left = rightLeft + "px";
if (k == 38) {
clearInterval(move);
move = setInterval(up, 10);
} else if (k == 40) {
clearInterval(move);
move = setInterval(down, 10);
}
}
function down() {
upDown++;
character.style.top = upDown + "px";
if (k == 39) {
clearInterval(move);
move = setInterval(right, 10);
} else if (k == 37) {
clearInterval(move);
move = setInterval(left, 10);
}
}
function up() {
upDown--;
character.style.top = upDown + "px";
if (k == 39) {
clearInterval(move);
move = setInterval(right, 10);
} else if (k == 37) {
clearInterval(move);
move = setInterval(left, 10);
}
}
#character {
width: 50px;
height: 50px;
background-color: black;
position: absolute;
}
#playGround {
position: relative;
background-color: gray;
border-style: solid;
border-color: blue;
width: 1515px;
height: 700px;
}
<div id="playGround">
<div id="character"></div>
</div>
There is a lot of work to be done here, but as for your specific question: you forgot to reset the 'k' variable. Add the line k = 0 to the die() function.
Good luck!

How to force div to not go out from another

Problem is simple but seems I can't get over it, div called ".player" shouldn't be going out from div ".play-ground", it should be moving only in its yellow space. Next thing which I'm trying to achieve is that I want a div same size of the red one, showing up for some time, so that the user can catch it with the red one and after that he gets points otherwise doesn't. Is there any way to do it? And how make div disapear after being catched?
var a = prompt("Provide nick");
while (a === "") {
a = prompt("Provide nick");
}
document.write("<p>Nick: " + a + "</p>");
/* -------- */
var ground = document.getElementsByClassName('play-ground')[0];
var player = document.getElementsByClassName('player')[0];
var points = document.getElementsByClassName('numba')[0];
var thing = document.getElementsByClassName('thing-tocatch')[0];
document.onkeydown = move;
var lefts = 0;
var tops = 0;
function move(e) {
console.log(e.keyCode);
if (e.keyCode == 68) {
lefts += 100;
player.style.left = lefts + "px";
points.innerHTML = lefts;
}
if (e.keyCode == 65) {
lefts -= 100;
player.style.left = lefts + "px";
}
if (e.keyCode == 83) {
tops += 100;
player.style.top = tops + "px";
}
if (e.keyCode == 87) {
tops -= 100;
player.style.top = tops + "px";
}
}
.play-ground {
position: relative;
background: yellow;
width: 800px;
height: 700px;
}
.player {
position: absolute;
background: red;
width: 100px;
height: 100px;
}
.thing-tocatch {
background: blue;
height: 100px;
width: 100px;
position: absolute;
margin: 200px 200px;
}
<div id="game">
<div class="points">
<h3>Points: <span class="numba">0</span></h3>
</div>
<div class="play-ground">
<div class="thing-tocatch">
</div>
<div class="player">
</div>
</div>
</div>
</div>
I cannot write whole the app here, but I just want to show you some things.
Try to write your code: one action - one function. You can see as I did. I've splitted up your move function on two: onKeyDown and movePlayer. It will help you to support your code when the app will become bigger.
You should store states of your subjects. For example I've created object Palyer where I store his coords (you used for that two vars: lefts and tops). It will be better if you will implement the same for all subjects in your app. For example, the Player has props: width, height, x, y, color. The ground has props: width, height, color. The thing also should have props as for player. You should store these states as global variables, because you will need to use them in different functions.
Your questions:
Next thing which I'm trying to achieve is that I want a div same size of the red one, showing up for some time, so that the user can catch it with the red one and after that he gets points otherwise doesn't. Is there any way to do it?. Your question contains answer. You need a function which will draw (document.createElement('div')) HTML element and after that you will be able to change its styles. OR you can create the thing before start (as you did with player) and keep it hidden (style display: none;)
And how make div disapear after being catched? You can remove thing from DOM or change style to display: none;
I advice you to find similar apps to check how other developers implement similar things:
Pong Clone In JavaScript
Snake Game in vanilla js
var a = prompt("Provide nick");
while (a === "") {
a = prompt("Provide nick");
}
document.write("<p>Nick: " + a + "</p>");
/* -------- */
var ground = document.getElementsByClassName('play-ground')[0];
var player = document.getElementsByClassName('player')[0];
var points = document.getElementsByClassName('numba')[0];
var thing = document.getElementsByClassName('thing-tocatch')[0];
document.onkeydown = onKeyDown;
var Player = {x: 0, y: 0};
var STEP = 100;
function onKeyDown (e) {
console.log(e.keyCode);
var x = Player.x;
var y = Player.y;
if (e.keyCode == 68) {
x += STEP;
}
if (e.keyCode == 65) {
x -= STEP;
}
if (e.keyCode == 83) {
y += STEP;
}
if (e.keyCode == 87) {
y -= STEP;
}
movePlayer(x, y);
}
function movePlayer (x, y) {
if (!isCoordsInsideGround(x, y)) return;
Player.x = x || 0;
Player.y = y || 0;
player.style.left = Player.x + "px";
player.style.top = Player.y + "px";
}
function isCoordsInsideGround (x, y) {
if (x < 0 || ground.offsetWidth - STEP < x) {
return false;
}
if (y < 0 || ground.offsetHeight - STEP < y) {
return false;
}
return true;
}
.play-ground {
position: relative;
background: yellow;
width: 800px;
height: 700px;
}
.player {
position: absolute;
background: red;
width: 100px;
height: 100px;
}
.thing-tocatch {
background: blue;
height: 100px;
width: 100px;
position: absolute;
margin: 200px 200px;
}
<div id="game">
<div class="points">
<h3>Points: <span class="numba">0</span></h3>
</div>
<div class="play-ground">
<div class="thing-tocatch">
</div>
<div class="player">
</div>
</div>
</div>
</div>

Stop moving element when he outside of parent element

So, I have an event listener keydown on arrow right, when you push the square moving on xPX but my parent element this w and h
set a 100px for example, and I would like to stop moving and I can't, I try with element.offsetWidth > 0 so them you can move.
Please look this fiddle : FIDDLE
Few errors in your code. I've commented fixes. Here is how i made it for the right arrow - you can apply same logic to the rest of the moves...
Code:
const carre = document.querySelector('.carre');
const main = document.querySelector('.main');
const w = main.offsetWidth - carre.offsetWidth; // this was wrong in your code
carre.style.left="0px"; // set start position
document.addEventListener('keyup', (event) => {
const positionLeft = parseInt(carre.style.left); //i've used style.left, rather, it gives expected numbers (10,20,30....)
if(event.keyCode == '39') {
if (positionLeft < w) { // this was fixed too
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
})
DEmo:
const carre = document.querySelector('.carre');
const main = document.querySelector('.main');
const w = main.offsetWidth - carre.offsetWidth; // this was wrong in your code
carre.style.left="0px"; // set start position
document.addEventListener('keyup', (event) => {
const positionLeft = parseInt(carre.style.left); //i've used style.left, rather, it gives expected numbers (10,20,30....)
if(event.keyCode == '39') {
if (positionLeft < w) { // this was fixed too
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
})
* {
box-sizing:border-box;
}
.carre {
position:absolute;
left: 0;
width: 50px;
height: 50px;
background-color: red;
}
.main {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #000;
}
<main class="main">
<div class="carre"></div>
</main>
I rebuild your code:
document.addEventListener('keydown', (event) => {
const w = main.getBoundingClientRect().right - carre.getBoundingClientRect().right;
const positionLeft = carre.getBoundingClientRect().left;
if(event.keyCode == '39') {
if (w >= 0) {
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
if (event.keyCode == '37') {
if (w >= 0) {
carre.style.left = (positionLeft) - 10 + 'px';
}else {
carre.style.left = '0'
}
}
})

Can't start and stop animation that runs in a constant loop

To simplify this question I have created two divs: when you click on the orange box the blue box below it will move back and forth in a continuous loop. What I want to be able to do is:
Click the orange box to start and STOP the blue box loop
After starting and stopping, the blue box will stop and continue each time where it left off.
I've tried just about everything and can't get it to work. Any advice would be greatly appreciated.
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
hoverSlideBox.onclick = function() {
var pos = 0;
var moveLeft = false;
var stopAnimate = false;
init();
function init() {
setInterval(boxRight, 5);
}
function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
}
function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
You need to move some variables out of the onclick function so that they are not reset each time you click on the orange box. That, together with clearInterval, will give you a start/stop button.
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var running = false;
var intervalId;
var pos = 0;
var moveLeft = false;
hoverSlideBox.onclick = function() {
init();
function init() {
if (!running) {
intervalId = setInterval(boxRight, 5);
running = true;
} else {
clearInterval(intervalId);
running = false;
}
}
function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
}
function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
To do this, you can use clearInterval to stop the movement. To make it resume when you click again, you just need to have your position variable in a permanent scope (I move it to the global scope for simplicity).
Changed code:
var pos = 0;
var moveLeft = false;
var stopAnimate = false;
var slideInterval;
hoverSlideBox.onclick = function() {
init();
function init() {
if (slideInterval) {
clearInterval(slideInterval);
slideInterval = null;
} else {
slideInterval = setInterval(boxRight, 5);
}
}
Snippet:
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var pos = 0;
var moveLeft = false;
var stopAnimate = false;
var slideInterval;
hoverSlideBox.onclick = function() {
init();
function init() {
if (slideInterval) {
clearInterval(slideInterval);
slideInterval = null;
} else {
slideInterval = setInterval(boxRight, 5);
}
}
function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
}
function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
setInterval returns interval id which you can use to cancel the interval using clearInterval
You could cancel the timer as the other answer says, or use requestAnimationFrame which is specifically designed for animations like these. See documentation here
This way we can simply check if stopAnimating is set before queueing up our next frame. You could do the same thing with setInterval if you wanted to, but requestAnimationFrame is probably better.
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
hoverSlideBox.onclick = function() {
var pos = 0;
var moveLeft = false;
var stopAnimate = false;
init();
function init() {
animate();
}
function animate(){
// stop animating without queueing up thenext frame
if (stopAnimate) return;
//queue up theh next frame.
requestAnimationFrame(boxRight);
}
function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
animate();
}
function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
Your code doesn't clear the interval when box is clicked again. setInterval executes a function every number of given seconds. To stop it, you have use the function clearInterval, passing the timer id that the function setInterval returned.
Also, your code can be better organized. I've refactorized it base in the following advices:
Don't use different functions for each direction. Your code have two different functions (moveLeft and moveRight) that are almost the same. Instead, use a simpler function that increments position given the current direction. Use a simple variable with the position increment, using -1 for left movement and +1 for right movement. If you have to modify the way the box moves you only have to change the moveBox function.
Use a function to check if the box have reached the boundaries. In general is good to have small functions that do one simple thing. In your code, boundaries check is splited in the two movement functions. In the proposed code the check code is a separate function where you can modify boundaries easily in the future if needed, instead of changing them in different places of your code.
Don't put all your logic in the click listener. Again, use simple functions that perform one simple task. The click listener should do a simple task, that's switching animation on and off. Initialization code should be in its onw function.
Again, for simplicity, use a simple function as the function executed by setInterval. If not, you would have to change the function that is executed by the setInterval function: moveRight when box is moving to the right and moveLeft when the box is moving to the left. This makes the code more complex and hard to debug and mantain.
Those advices are not very useful with a small code like this, but its benefits are more visible when your code gets more complex.
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var pos = 0;
var direction = 1;
var animate = false;
var intervalHandler;
hoverSlideBox.onclick = function() {
if (animate) {
stop();
}
else {
init();
}
}
function init() {
animate = true;
intervalHandler = setInterval(moveBox, 5);
}
function stop() {
animate = false;
clearInterval(intervalHandler);
}
function tic() {
if (animate) {
moveBox();
}
}
function checkBoundaries() {
if (pos == 500) {
direction = -1;
}
else if (pos == 0) {
direction = 1;
}
}
function moveBox() {
pos += direction;
slidingBox.style.left = pos + 'px';
checkBoundaries();
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
Try this snippet, it should work aswell
var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var moveLeft = false;
var pos = 0;
var intervalID = null;
hoverSlideBox.onclick = function(){
if (intervalID) {
clearInterval(intervalID);
intervalID = null;
} else {
intervalID = setInterval(function () {
pos += moveLeft ? -1 : 1;
slidingBox.style.left = pos + 'px';
moveLeft = pos >= 500 ? true : pos <= 0 ? false : moveLeft;
}, 5);
}
}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;">
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;">

JavaScript - Stop laser once its in its incrementation cycle

To see a working example simply copy code into notepad++ and run in chrome as a .html file, I have had trouble getting a working example in snippet or code pen, I would have given a link to those websites if I could get it working in them.
The QUESTION is; once I fire the laser once it behaves exactly the way I want it to. It increments with lzxR++; until it hits boarder of the game arena BUT if I hit the space bar WHILST the laser is moving the code iterates again and tries to display the laser in two places at once which looks bad and very choppy, so how can I get it to work so the if I hit the space bar a second time even whilst the laser was mid incrementation - it STOPS the incrementing and simply shoots a fresh new laser without trying to increment multiple lasers at once???
below is the Code:
<html>
<head>
<style>
#blueCanvas {
position: absolute;
background-color: black;
width: 932px;
height: 512px;
border: 1px solid black;
top: 20px;
left: 20px;
}
#blueBall {
position: relative;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 10px;
border-radius: 100%;
top: 0px;
left: 0px;
}
#laser {
position: absolute;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 1px;
top: 10px;
left: 10px;
}
#pixelTrackerTop {
position: absolute;
top: 530px;
left: 20px;
}
#pixelTrackerLeft {
position: absolute;
top: 550px;
left: 20px;
}
</style>
<title>Portfolio</title>
<script src="https://ajax.googleapis.com/
ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
document.addEventListener("keydown", keyBoardInput);
var topY = 0;
var leftX = 0;
var lzrY = 0;
var lzrX = 0;
function moveUp() {
var Y = document.getElementById("blueBall");
topY = topY -= 1;
Y.style.top = topY;
masterTrack();
if (topY < 1) {
topY = 0;
Y.style.top = topY;
};
stopUp = setTimeout("moveUp()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYup();
console.log('moveUp');
};
function moveDown() {
var Y = document.getElementById("blueBall");
topY = topY += 1;
Y.style.top = topY;
masterTrack();
if (topY > 500) {
topY = 500;
Y.style.top = topY;
};
stopDown = setTimeout("moveDown()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYdown();
console.log('moveDown');
};
function moveLeft() {
var X = document.getElementById("blueBall");
leftX = leftX -= 1;
X.style.left = leftX;
masterTrack();
if (leftX < 1) {
leftX = 0;
Y.style.leftX = leftX;
};
stopLeft = setTimeout("moveLeft()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXleft();
console.log('moveLeft');
};
function moveRight() {
var X = document.getElementById("blueBall");
leftX = leftX += 1;
X.style.left = leftX;
masterTrack();
if (leftX > 920) {
leftX = 920;
Y.style.leftX = leftX;
};
stopRight = setTimeout("moveRight()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXright();
console.log('moveRight');
};
function masterTrack() {
var pxY = topY;
var pxX = leftX;
document.getElementById('pixelTrackerTop').innerHTML =
'Top position is ' + pxY;
document.getElementById('pixelTrackerLeft').innerHTML =
'Left position is ' + pxX;
};
function topStop() {
if (topY <= 0) {
clearTimeout(stopUp);
console.log('stopUp activated');
};
if (topY >= 500) {
clearTimeout(stopDown);
console.log('stopDown activated');
};
};
function leftStop() {
if (leftX <= 0) {
clearTimeout(stopLeft);
console.log('stopLeft activated');
};
if (leftX >= 920) {
clearTimeout(stopRight);
console.log('stopRight activated');
};
};
function stopConflictYup() {
clearTimeout(stopDown);
};
function stopConflictYdown() {
clearTimeout(stopUp);
};
function stopConflictXleft() {
clearTimeout(stopRight);
};
function stopConflictXright() {
clearTimeout(stopLeft);
};
function shootLaser() {
var l = document.getElementById("laser");
var lzrY = topY;
var lzrX = leftX;
fireLaser();
function fireLaser() {
l.style.left = lzrX; /**initial x pos **/
l.style.top = topY; /**initial y pos **/
var move = setInterval(moveLaser, 1);
/**continue to increment laser unless IF is met**/
function moveLaser() { /**CALL and start the interval**/
var bcrb = document.getElementById("blueCanvas").style.left;
if (lzrX > bcrb + 920) {
/**if the X axis of the laser goes beyond the
blueCanvas 0 point by 920 then stop incrementing the laser on its X
axis**/
clearInterval(move);
/**if statement was found true so stop increment of laser**/
} else {
lzrX++;
l.style.left = lzrX;
};
};
};
};
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
shootLaser();
};
if (i == 38) {
if (topY > 0) {
moveUp();
};
};
if (i == 40) {
if (topY < 500) {
moveDown();
};
};
if (i == 37) {
if (leftX > 0) {
moveLeft();
};
};
if (i == 39) {
if (leftX < 920) {
moveRight();
};
};
};
/**
!! gradual progression of opacity is overall
!! being able to speed up element is best done with setTimout
!! setInterval is constant regards to visual speed
!! NEXT STEP IS ARRAYS OR CLASSES
IN ORDER TO SHOOT MULITPLE OF SAME ELEMENT? MAYBEE?
var l = document.getElementById("laser");
lzrX = lzrX += 1;
l.style.left = lzrX;
lzrY = topY += 1;
l.style.top = lzrY;
**/
</SCRIPT>
</head>
<div id="blueCanvas">
<div id="laser"></div>
<div id="blueBall">
</div>
</div>
<p id="pixelTrackerTop">Top position is 0</p>
<br>
<p id="pixelTrackerLeft">Left position is 0</p>
</body>
</html>
Solved the problem with using a variable called "g" and incrementing it once the laser is shot!
var g = 0;
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
if (g < 1) {
shootLaser();
g++;
};
};

Categories