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>
Related
I am trying to transform this element into a standard web component using Lit. (https://www.w3schools.com/howto/howto_js_image_comparison.asp)
I totally new to Lit and to web components and am struggling to select elements from the shadow DOM. Right now, I am stuck with the var x inside the initComparisons() function. I am aware that the document object does not exist in the shadow dom and must be replaced by renderRoot, however, I am not sure either If I am selecting the elements the right way or what does replace the window object... Do you notice something wrong with this code? I am stuck at the first lines of the initComparisons() function as x always returns null no matter what I do....
Any help will be appreciated.
Thank you very much.
import {
LitElement,
css,
html,
} from "https://cdn.jsdelivr.net/gh/lit/dist#2/all/lit-all.min.js";
export class Comparator extends LitElement {
static properties = {
baseImage: "",
imageWidth: "",
imageHeight: "",
altImage: "",
};
// Define scoped styles right with your component, in plain CSS
static styles = css`
* {
box-sizing: border-box;
}
.img-comp-container {
position: relative;
height: 200px; /*should be the same height as the images*/
}
.img-comp-img {
position: absolute;
width: auto;
height: auto;
overflow: hidden;
}
.img-comp-img img {
display: block;
vertical-align: middle;
}
.img-comp-slider {
position: absolute;
z-index: 11;
cursor: ew-resize;
/*set the appearance of the slider:*/
width: 40px;
height: 40px;
background-color: #2196f3;
opacity: 0.7;
border-radius: 50%;
}
.border-slider {
position: absolute;
z-index: 10;
cursor: ew-resize;
/*set the appearance of the slider:*/
width: 5px;
height: 130%;
background-color: red;
opacity: 1;
}
.border-slider::after {
content: url("./separator.svg");
position: absolute;
width: 30px;
height: 30px;
background: red;
top: calc(50% - 15px);
left: calc(50% - 15px);
}
`;
constructor() {
super();
// Declare reactive defaults
this.baseImage = "https://api.lorem.space/image/house?w=800&h=600";
this.altImage = "https://api.lorem.space/image/house?w=800&h=600";
this.imageWidth = "800px";
this.imageHeight = "600px";
}
connectedCallback() {
super.connectedCallback();
this.initComparisons();
}
// Render the UI as a function of component state
render() {
return html`
<div class="img-comp-container">
<div class="img-comp-img">
<img
src="${this.baseImage}"
width="${this.imageWidth}"
height="${this.imageHeight}"
/>
</div>
<div id="img-comp-overlay" class="img-comp-img">
<img
src="${this.altImage}"
width="${this.imageWidth}"
height="${this.imageHeight}"
/>
</div>
</div>
`;
}
//HELPER FUCTIONS GO HERE
initComparisons() {
var x, i;
/*find all elements with an "overlay" class:*/
x = this.renderRoot.querySelector("#img-comp-overlay");
for (i = 0; i < x.length; i++) {
/*once for each "overlay" element:
pass the "overlay" element as a parameter when executing the compareImages function:*/
compareImages(x[i]);
}
function compareImages(img) {
var slider,
img,
clicked = 0,
w,
h;
/*get the width and height of the img element*/
w = img.offsetWidth;
h = img.offsetHeight;
/*set the width of the img element to 50%:*/
img.style.width = w / 2 + "px";
/*create slider:*/
slider = this.renderRoot.createElement("DIV");
slider.setAttribute("class", "border-slider");
/*insert slider*/
img.parentElement.insertBefore(slider, img);
/*position the slider in the middle:*/
slider.style.top = h / 2 - slider.offsetHeight / 2 + "px";
slider.style.left = w / 2 - slider.offsetWidth / 2 + "px";
/*execute a function when the mouse button is pressed:*/
slider.addEventListener("mousedown", slideReady);
/*and another function when the mouse button is released:*/
this.renderRoot.addEventListener("mouseup", slideFinish);
/*or touched (for touch screens:*/
slider.addEventListener("touchstart", slideReady);
/*and released (for touch screens:*/
window.addEventListener("touchend", slideFinish);
function slideReady(e) {
/*prevent any other actions that may occur when moving over the image:*/
e.preventDefault();
/*the slider is now clicked and ready to move:*/
clicked = 1;
/*execute a function when the slider is moved:*/
window.addEventListener("mousemove", slideMove);
window.addEventListener("touchmove", slideMove);
}
function slideFinish() {
/*the slider is no longer clicked:*/
clicked = 0;
}
function slideMove(e) {
var pos;
/*if the slider is no longer clicked, exit this function:*/
if (clicked == 0) return false;
/*get the cursor's x position:*/
pos = getCursorPos(e);
/*prevent the slider from being positioned outside the image:*/
if (pos < 0) pos = 0;
if (pos > w) pos = w;
/*execute a function that will resize the overlay image according to the cursor:*/
slide(pos);
}
function getCursorPos(e) {
var a,
x = 0;
e = e.changedTouches ? e.changedTouches[0] : e;
/*get the x positions of the image:*/
a = img.getBoundingClientRect();
/*calculate the cursor's x coordinate, relative to the image:*/
x = e.pageX - a.left;
/*consider any page scrolling:*/
x = x - window.pageXOffset;
return x;
}
function slide(x) {
/*resize the image:*/
img.style.width = x + "px";
/*position the slider:*/
slider.style.left = img.offsetWidth - slider.offsetWidth / 2 + "px";
}
}
}
}
customElements.define("image-compare", Comparator);
connectedCallback() is likely too early to call this.initComparison() as the elements might not have been populated within the shadowroot. That happens on first render so you can grab those elements in firstUpdated() instead.
based on this this tutorial on w3 schools I wrote a function(move) that animates an element(div) using the setInterval() method, my problem is when I try to call the function move() several times the div does an unexpected behavior, I tried to use async/await but it didn't work.
async function moveArray(destination) {
//move through array of addresses
for (let i = 0; i < destination.length - 1; i++) {
await move(destination[i], destination[i + 1]);
}
}
async function move(pos, add) {
//moves element from position to address
var elem = document.getElementById("object");
var id = setInterval(frame, 15);
function frame() {
if (pos.x == add.x && pos.y == add.y) {
clearInterval(id);
return;
} else {
//if element haven't reached its target
// we add/substract 1 from the address and update styling
if (pos.x != add.x) {
pos.x += add.x > pos.x ? 1 : -1;
elem.style.left = pos.x + "px";
}
if (pos.y != add.y) {
pos.y += add.y > pos.y ? 1 : -1;
elem.style.top = pos.y + "px";
}
}
}
}
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#object {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
<button onclick="moveArray( [{x:0,y:0}, {x:140, y:150}, {x:130, y:110}, {x:70, y:65}] )">
move
</button>
<div id="container">
<div id="object"></div>
//object to be animated
</div>
The weird behavior is caused because the move function is being called multiple times simultaneously in the for loop. This happens because your async functions do not know when they are done.
Instead of making move async, which it doesn't have to if it is not awaiting anything, return a Promise from the start and call you animation code inside of it. When the point is reached when animation has to end, resolve the promise.
Doing it like this will make your await statement in the for loop wait for the move function to reach the resolve call before continuing with the next animation.
async function moveArray(destination) {
//move through array of addresses
for (let i = 0; i < destination.length - 1; i++) {
await move(destination[i], destination[i + 1]);
}
}
function move(pos, add) {
return new Promise(resolve => {
var elem = document.getElementById("object");
var id = setInterval(frame, 15);
function frame() {
if (pos.x == add.x && pos.y == add.y) {
clearInterval(id);
// Fulfill promise when position is reached.
resolve();
} else {
if (pos.x != add.x) {
pos.x += add.x > pos.x ? 1 : -1;
elem.style.left = pos.x + "px";
}
if (pos.y != add.y) {
pos.y += add.y > pos.y ? 1 : -1;
elem.style.top = pos.y + "px";
}
}
}
});
}
<!DOCTYPE html>
<html>
<head>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#object {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
</head>
<body>
<button onclick="moveArray( [{x:0,y:0}, {x:140, y:150}, {x:130, y:110}, {x:70, y:65}] )">
move
</button>
<div id="container">
<div id="object"></div>
//object to be animated
</div>
<script src="animation.js"></script>
</body>
</html>
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++;
};
};
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
The webpage I'm trying to create has a bidirectional sliding animation on it. However the animation is only partially working. To be more precise, the animation slides up, but it only slides down partway. Here's my JavaScript:
function showLayer() {
var hiddenLayer = document.getElementById("mainmenu");
var layerPosition = parseInt(hiddenLayer.style.top);
if (layerPosition > 315) {
hiddenLayer.style.top = (layerPosition - 5) + "px";
setTimeout("showLayer()", 20);
}
}
function hideLayer() {
var hiddenLayer = document.getElementById("mainmenu");
var layerPosition = parseInt(hiddenLayer.style.top);
if (layerPosition <= 315) {
hiddenLayer.style.top = (layerPosition + 5) + "px";
setTimeout("hideLayer()", 20);
}
}
Notice on the fourth line of the hideLayer function, I have the condition set to <= 315, this is due to the fact that setting it equal to 315 causes the element to move only a few pixels in either direction after clicking the trigger element. Here's the HTML elements I have dedicated to the animation:
<div id="mainbutton" onclick="showLayer('mainmenu'); hideLayer('mainmenu')"></div>
<div id="mainmenu" style="position: absolute; top: 690px; left: 9px;"
onclick="showLayer('mainmenu')"> </div>
And here are the styles for them:
div#mainmenu { width: 600px; height: 350px; border-style: solid; background-color:
rgb(0, 0, 0) ; border-width: 3px; border-top-right-radius: 7px; border-top-left-
radius: 7px; }
div#mainbutton { position: absolute; top: 674px; left: 12px; width: 28px; height:
28px; border-style: solid; border-color: rgb(255, 255, 255); border-width: 1px; border-
radius: 4px; }
And the fiddle : http://jsfiddle.net/JAtLA/
I had to put some of the styles inline with the HTML because the animation wouldn't work any other way. At first I thought the problem had solely lain in the if conditional of the hideLayer function. But after tweaking it I'm not so sure now.
I don't know if it's what you want but here is my answer :
There is a problem of logic in your code. You wrote
if(layerPosition<=315){
hiddenLayer.style.top = (layerPosition + 5) + "px";}
It means that if the top is 315 or less, the top will increase until it arrives to 316. But in the first function, you say it to stop at 315. So the function hideLayer will just get it moving from 1 pixel.
The solution is to tell him <400 instead of <=315 (or something higher than 400).
Here is a modified fiddle : http://jsfiddle.net/7egr7/2/
It looks like "hideLayer" will stop if (layerPosition <= 315). Is that really what you want? It happens after 1 iteration.
Note that the y axis goes down the screen (i.e. zero is at the top).
Clicking the button will call showLayer, and then hideLayer.
If the menu is open (i.e. layerPosition > 315), showLayer will not do anything (i guess that is what you intend), and hideLayer will make the menu go up by 5 (from 315 to 320).
On the next iteration of hideLayer (layerPosition <= 315) will be false, so it will not do anything.
Try this:
var open = false;
function showLayer() {
if (open)
return;
var hiddenLayer = document.getElementById("mainmenu");
var layerPosition = parseInt(hiddenLayer.style.top);
if (layerPosition > 315) {
hiddenLayer.style.top = (layerPosition - 5) + "px";
setTimeout("showLayer()", 20);
}
else {
open = true;
}
}
function hideLayer() {
if (!open)
return;
var hiddenLayer = document.getElementById("mainmenu");
var layerPosition = parseInt(hiddenLayer.style.top);
if (layerPosition <= 685) {
hiddenLayer.style.top = (layerPosition + 5) + "px";
setTimeout("hideLayer()", 20);
}
else {
open = false;
}
}
In the html, I would like to check if the thing is open or closed before doing anything.
<div id="mainbutton" onclick="if (!open) { showLayer('mainmenu'); } else { hideLayer('mainmenu'); }">
but layerPosition <= 685 is the only change that really matters.