update .style attributes with setInterval - javascript

I'm trying to move the position of a div element at set intervals however the setInterval method executes once and then stops. setInterval() doesn't update .style.transform repeatedly every 200 milliseconds as intended.
<!DOCTYPE html>
<html>
<head>
<title>Snake game</title>
<style type="text/css">
.container {
width: 500px;
height: 500px;
border: 2px solid black;
}
#snakehead {
width: 5px;
height: 5px;
background: pink;
position: relative;
left: 0px;
}
</style>
<script type="text/javascript" src="snake.js"></script>
</head>
<body>
<div class="container">
<div id="snakehead"></div>
</div>
</body>
</html>
Javascript: Ideally I'd also like to be able to move the snakehead in any direction with vx and vy. Anyway to put those values into .style.transform = translateX()?
function snakepos() {
var x = 0;
var y = 0;
var vx = 1;
var vy = 0;
return {
move: function() {
x += vx;
y += vy;
var snakehead = document.querySelector("#snakehead");
snakedhead.style.left = "5px";
}
};
}
window.onload = function() {
console.log("hi");
var container = document.querySelector(".container");
var snake = snakepos();
setInterval(function() {
snake.move();
}, 200);
}
I know this can be done much easier in jQuery with .css but I'd to how this can be done in vanilla javascript. Thank you in advance.

snakehead.style.left = (snakedhead.style.left + "5px");
or
snakehead.style.left = (snakedhead.style.left - "5px");

I'd recommend something in a style a bit more familiar to me:
function snakepos() {
this.x = 0;
this.y = 0;
this.vx = 1;
this.vy = 1;
this.snakehead = document.querySelector("#snakehead");
var me = this;
this.move = function() {
me.x += me.vx;
me.y += me.vy;
me.snakehead.style.top = me.y + "px";
me.snakehead.style.left = me.x + "px";
};
return this;
}
console.log("hi");
var container = document.querySelector(".container");
var snake = new snakepos();
setInterval(function() {
snake.move();
}, 200);
See fiddle: https://jsfiddle.net/theredhead/td8opb0b/1/

Related

Clicking on an image not working as intended

I made a game where you need to click the image on the left side of the screen that you do not see on the opposite side to get to the next level. For some reason, when you click any image on the left side you still go to the next level. When you click the wrong image it should say game over. Right now it only does that when the whitespace is clicked. Any tips?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Matching Game</title>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid;
}
</style>
</head>
<body onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
<script >
let numberOfFaces = 5;
const theLeftSide = document.querySelector("#leftSide");
const theRightSide = document.querySelector("#rightSide");
function generateFaces() {
for (let i = 0; i < numberOfFaces; i++) {
let face = document.createElement("img");
face.src = 'images/smile.png';
const randomTop = Math.floor(Math.random() * 400) + 1;
const randomLeft = Math.floor(Math.random() * 400) + 1;
face.style.top = randomTop + 'px';
face.style.left = randomLeft + 'px';
theLeftSide.appendChild(face);
theLeftSide.lastChild.addEventListener('click', nextLevel);
document.body.addEventListener('click', gameOver);
}
const leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
function nextLevel(event) {
event.stopPropagation();
numberOfFaces += 5;
while (theLeftSide.firstChild) {
theLeftSide.removeChild(theLeftSide.firstChild);
}
while (theRightSide.firstChild) {
theRightSide.removeChild(theRightSide.firstChild);
}
generateFaces();
}
function gameOver() {
alert('Game Over!');
document.body.removeEventListener('click', gameOver);
theLeftSide.lastChild.removeEventListener('click', nextLevel);
}
}
</script>
</body>
</html>
notice
for (let i = 0; i < numberOfFaces; i++) {
let face = document.createElement("img");
...
theLeftSide.appendChild(face);
// you do this in every loop
theLeftSide.lastChild.addEventListener('click', nextLevel);
}
put the theLeftSide.lastChild.addEventListener('click', nextLevel); outside loop for it to work

Im trying to create element by clicking button with position of moving existing element but it doesnt work

var arrow = document.getElementById("arrow");
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "black";
arrows.style.height = "80" + "px";
arrows.style.width = "3" + "px";
var arrowX = parseInt(document.arrow.style.left);
var arrowY = parseInt(document.arrow.style.top);
document.arrows.style.left = arrowX + "px";
document.arrows.style.top = arrowY + "px";
};
When I run it and click button which runs function shot it says it cannot read property "style" of undefined. It also spawns a new element on position it would spawn without any position defining.
Yep, my ids are correct.
Html:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="arrow"><div>
<button id="button" onclick="shot();"> Shot! </button>
</body>
</html>
CSS:
#arrow {
background-color: black;
height: 80px;
width: 1.5px;
position: relative;
left: 0px;
top: 0px;
}
Here is full project JS, which u dont need. Its not complete. There is button faster but it doesnt work, idk why. It should be archery game
var arrow = document.getElementById("arrow");
var arrowPos = -50;
var speed = 1000;
var speed2 = speed/100;
function arrow_move_right() {
arrowPos += 1;
arrow.style.left = arrowPos + "px";
if (arrowPos >= 280) {
return arrow_move_left()
}
else {
setTimeout(arrow_move_right, speed2);
};
};
function arrow_move_left() {
arrow = document.getElementById("arrow");
arrowPos -= 1;
arrow.style.left = arrowPos + "px";
if (arrowPos <= -50) {
return arrow_move_right()
}
setTimeout(arrow_move_left, speed2);
};
function faster() {
speed -= 100;
alert(speed)
}
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "black";
arrows.style.height = "80" + "px";
arrows.style.width = "1.5" + "px";
var arrowX = parseInt(arrow.style.left);
var arrowY = parseInt(arrow.style.top);
alert(arrowX);
alert(arrowY);
// arrows.style.left = arrowX;
// arrows.style.top = arrowY;
arrows.style.pos = "relative";
arrows.style.top = -50 + "px";
};
Hope this is what you are looking for!
var arrow = document.getElementById("arrow");
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "blue";
arrows.style.height = "80px";
arrows.style.width = "3px";
arrows.style.position = "absolute";
arrows.style.top = arrow.offsetTop + "px";
arrows.style.left = arrow.offsetLeft + "px";
};
#arrow {
height: 80px;
width: 3px;
background: black;
position: relative;
-webkit-animation: move 5s infinite; /* Safari 4.0 - 8.0 */
animation: move 5s infinite;
}
/* Styles for animating arrow */
/* Safari 4.0 - 8.0 */
#-webkit-keyframes move {
from {left: 0px;}
to {left: 400px;}
}
#keyframes move {
from {left: 0px;}
to {left: 400px;}
}
<div id="arrow"></div>
<button id="button" onclick="shot();"> Shot! </button>
Here is what I mean....
var arrow = document.getElementById("arrow");
function shot() {
var arrows = document.createElement("div");
document.body.appendChild(arrows);
arrows.style.backgroundColor = "black";
arrows.style.height = "80" + "px";
arrows.style.width = "3" + "px";
var arrowX = parseInt(arrow.style.left);
var arrowY = parseInt(arrow.style.top);
arrows.style.left = arrowX + "px";
arrows.style.top = arrowY + "px";
};
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="arrow"><div>
<button id="button" onclick="shot();"> Shot! </button>
</body>
</html>

Dom html javascript about onclick

I want to generate five image imgs first in left side, then remove the lastchild of it and copy the rest to the right side. If user clicks the extra img in left side, then clear all and generate more 5(10) img in left and copy 9 to the right side, and so on. If user clicks the wrong place, alert ("game over").Here is my code:
<html>
<head>
<style>
img{
position: absolute;
}
div{
position: absolute;
width: 500px;
height: 500px;
}
#rightSide { left: 500px;
border-left: 1px solid black;
}
</style>
<script>
var numberOfFaces = 5;
function generateFaces(){
var theLeftSide = document.getElementById("leftSide");
for (var i = 0; i < numberOfFaces; i++){
var img = document.createElement("img");
img.src = "smile.png";
var randomTop = Math.random() * 400;
var randomLeft = Math.random() * 400;
img.style.top = randomTop + "px";
img.style.left = randomLeft + "px";
theLeftSide.appendChild(img);
}
var theRightSide = document.getElementById("rightSide");
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightSide").appendChild(leftSideImages);
var theBody = document.getElementByTagName("body")[0];
theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
while (theBody.firstChild){
theBody.removeChild(theBody.firstChild);
}
numberOfFaces += 5;
generateFaces();
}
theBody.onclick = function gameover(){
alert("Game Over");
thBody.onclick = null;
theLeftSide.lastChild.onclick = null;
}
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>click on the extra smiling face on the left</p>
<div id = "leftSide">
</div>
<div id = "rightSide">
</div>
</body>
</html>
I could generate and clone at first time, but when I click, nothing happens, so what is the problem?
This may be a typing error.
var theBody = document.getElementsByTagName("body")[0];
your code: var theBody = document.getElementByTagName("body")[0];
I suggest to use a good editor for html. I fixed the error with Jetbrain phpStorm but better ones may exist.
Bellow is a modified version that worked for me. Notice that in this version I added the events on all children instead of the whole document body. I don't know but for me it feels more accurate not to end the game on a user clicks on a white space for example.
<html>
<head>
<style>
img{
position: absolute;
}
div{
position: absolute;
width: 500px;
height: 500px;
}
#rightSide { left: 500px;
border-left: 1px solid black;
}
</style>
<script>
var numberOfFaces = 5;
var theBody;
var theLeftSide;
var theRightSide;
function generateFaces(){
theBody = document.getElementsByTagName("body")[0];
theLeftSide = document.getElementById("leftSide");
theRightSide = document.getElementById("rightSide");
for (var i = 0; i < numberOfFaces; i++){
var img = document.createElement("img");
img.src = "smile.png";
var randomTop = Math.random() * 400;
var randomLeft = Math.random() * 400;
img.style.top = randomTop + "px";
img.style.left = randomLeft + "px";
if(theLeftSide != null)
theLeftSide.appendChild(img);
else
{
alert("Game Over");
return;
}
}
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightSide").appendChild(leftSideImages);
addEvents();
}
function addEvents(){
for(var i=0; i < theLeftSide.childNodes.length; i++){
theLeftSide.childNodes[i].onclick = nextLevel;
}
}
function removeEvents(){
for(var i=0; i < theLeftSide.childNodes.length; i++){
theLeftSide.childNodes[i].onclick = null;
}
}
function nextLevel(event){
if(this == theLeftSide.lastChild){
event.stopPropagation();
theLeftSide.innerHTML = "";
theRightSide.innerHTML = "";
numberOfFaces += 5;
generateFaces();
}
else
{
alert("Game Over");
removeEvents();
}
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>click on the extra smiling face on the left</p>
<div id = "leftSide">
</div>
<div id = "rightSide">
</div>
</body>
</html>

Stop javascript "animation" onclick div

I'm a beginner in javascript and I'm trying to make a very simple game. I know that my code is not the best, but i want to make it working. I want to stop function nahoru() or make it move to the other way and after it touches the bottom of the page/100%, make it repeat.
<html>
<head>
<script>
function naloud() {
var elem = document.getElementById("krtek");
elem.style.top = '100%';
var eleme = document.getElementById("krtek2");
eleme.style.top = '100%';
var elemen = document.getElementById("krtek3");
elemen.style.top = '100%';
}
var pos = 100;
var los = 0;
function nahoru() {
var elemend = document.getElementById("batn");
elemend.style.opacity = '0';
var elem = document.getElementById("krtek");
var id = setInterval(frame, 30);
function frame() {
if (pos == 0) {
clearInterval(id);
document.write('<center>GAME OVER<br>YOUR SCORE: ' + skore +
'<br>Press F5 for restart.')
} else {
pos = pos - 1;
elem.style.top = pos + '%';
}
}
}
var skore = 0;
function pric() {
skore++;
document.getElementById("skore").innerHTML = "Skore: " + skore;
elem.style.top = '+100%';
}
</script>
<style>
.prvni {
position: absolute;
width: 10%;
height: 110%;
left: 10%;
background-color: brown;
}
.druhy {
position: absolute;
width: 10%;
height: 110%;
left: 45%;
background-color: brown;
}
.treti {
position: absolute;
width: 10%;
height: 110%;
left: 80%;
background-color: brown;
}
</style>
</head>
<body onload="naloud()">
<button onclick="nahoru()" id="batn">START</button>
<div id="skore">Skore: 0</div>
<div id="krtek" class="prvni" onclick="pric()"></div>
<div id="krtek2" class="druhy" onclick="pric()"></div>
<div id="krtek3" class="treti" onclick="pric()"></div>
</body>
</html>
Declare id outside nahoru function,
like here
var pos = 100;
var los = 0;
var id = null;
Set interval in nahoru function,
like this (important, remove var from here)
id = setInterval(frame, 30);
Now clear interval in pric function
like this
function pric(elem) {
skore++;
clearInterval(id);
document.getElementById("skore").innerHTML = "Skore: " + skore;
elem.style.top = '+100%';
}
Working https://jsfiddle.net/ee1bdL5k/
You need declare this var outside from function, for the pric function:
var elem, eleme, elemen;
function naloud() {
elem = document.getElementById("krtek");
elem.style.top = '100%';
eleme = document.getElementById("krtek2");
eleme.style.top = '100%';
elemen = document.getElementById("krtek3");
elemen.style.top = '100%';
}

Creating Circles(div) and appending it to div#canvas

I am trying to create new circles as my pen hovers on window.
I am having issues where I cannot add circles to the page. It just hovers around. How would i be able to modify my code to add circles as it hovers.
<!doctype html>
<html>
<head>
<title> JavaScript Environment: Project </title>
<meta charset="utf-8">
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
#canvas {
background-color: yellow;
width: 100%;
height: 100%;
}
.pen {
position: absolute;
background-color: lightblue;
width: 10px;
height: 10px;
border-radius: 5px;
}
</style>
<script>
window.onload = function() {
function Circle(x, y) {
this.x = x;
this.y = y;
}
var canvas = document.getElementById("canvas");
canvas.onmousedown = function() {
mouseDown();
};
canvas.onmouseup = function() {
mouseUp()
};
canvas.onmousemove = function() {
mouseMove(event)
};
function mouseDown (){
console.log ("mouse down");
}
function mouseUp (){
console.log ("mouse up");
}
function mouseMove(e) {
var canvas = document.getElementById("canvas");
var pen = document.createElement("div");
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
pen.setAttribute("class", "pen");
pen.style.left = x + "px";
pen.style.top = y + "px";
document.getElementById("canvas").innerHTML = coor;
canvas.appendChild(pen);
addCircles(x, y);
console.log("location # " + x + " : " + y);
}
function addCircles(x, y) {
var canvas = document.getElementById("canvas");
var circle = document.createElement("div");
circle.setAttribute("class", "pen");
circle.style.left = x + "px";
circle.style.top = y + "px";
canvas.appendChild(circle);
}
canvas.addEventListener("mouseMove", mouseMove, false);
};
</script>
</head>
<body>
<div id="canvas"></div>
</body>
</html>
The problem is in the line document.getElementById("canvas").innerHTML = coor;
Try adding a span <span id="canvasText"></span> inside of your canvas div and then changing the above line to document.getElementById("canvasText").innerHTML = coor;.
As it stands, you "reset" the contents of the canvas every time the mouse moves, so the circles are instantly removed from it. Reset only the span inside the canvas to keep the circles around.

Categories