How can i call setInterval more than one time? - javascript

So, i want to call setInterval with a button multiple times, but when i press the button a second time nothing happens. I have searched for other similar questions but they are in jQuery and dont worked for me.
Edit: What i wan't to do is to repeat the animation by clicking the button.
var element, add, intervalo;
add = 0;
function start(){
intervalo = setInterval(interval, 50);
}
function interval() {
add = add + 25;
element = document.getElementById('teste');
element.style.left = add;
if (add > 300) {
clearInterval(intervalo);
intervalo = null;
element.style.left = 0;
}
}
#teste {
position: absolute;
}
<html>
<head>
<script src="js/main.js"></script>
<link rel="stylesheet" src="text/css" href="css/estilo.css">
</head>
<body>
<h1 id="teste">Ola</h1>
<button onclick="start()">Start</button>
</body>
</html>

You are not resetting your add variable so when the interval is triggered a second time it will go right to the clearInterval section.
var element, add, intervalo, btn, element;
add = 0;
btn = document.getElementById('btn');
element = document.getElementById('teste');
function start() {
btn.disabled = true;
intervalo = setInterval(interval, 50);
}
function interval() {
add = add + 25;
element.style.left = add + 'px';
if (add > 300) {
clearInterval(intervalo);
intervalo = null;
element.style.left = 0;
btn.disabled = false;
add = 0;
}
}
#teste {
position: absolute;
left: 0;
top: 0;
}
<html>
<head>
<script src="js/main.js"></script>
<link rel="stylesheet" src="text/css" href="css/estilo.css">
</head>
<body>
<h1 id="teste">Ola</h1>
<button id="btn" onclick="start()">Start</button>
</body>
</html>

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

How can I generate new set of smiling faces at random position after user click on extra smiling face?

I have been trying to get the smiley faces to generate in new random position by putting the function delete_all_children() at appropriate locations, but everytime, it won't run properly. Instead, if I ignore the randomized location after finding the extra picture, the game runs properly but it is a build up from existing smiley faces, which makes the game easier.
I want the new faces to generate in random location.
Please help!
<DOCTYPE! html>
<html>
<head>
<title>Matching Game - Smiling :)</title>
<style>
div, img {position: absolute;}
div {width: 500px; height: 500px;}
#rightSide {left: 500px; border-left: 1px solid black}
</style>
<script type="text/javascript">
var numberOfFace = 5;
var count = 0;
var theBody = document.getElementsByTagName("body")[0];
function generateFaces() {
var theLeftSide = document.getElementById('leftSide');
var theRightSide = document.getElementById('rightSide');
while (count < numberOfFace) {
var top_random = (Math.random() * 400);
var left_random = (Math.random() * 400);
var smiling_face = document.createElement("img");
smiling_face.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiling_face.style.top = Math.floor(top_random) + "px";
smiling_face.style.left = Math.floor(left_random) + "px";
theLeftSide.appendChild(smiling_face);
count ++;
};
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
theLeftSide.lastChild.onclick = function nextLevel(event) {
event.stopPropagation();
numberOfFace += 5;
generateFaces();
};
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
function delete_all_children() {
var theNode = document.getElementById("theBody");
while (theNode.firstChild) {
theNode.removeChild(theNode.firstChild);
};
};
};
</script>
</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>
</body>
</html>

Why does the onclick event listener gets removed?

I am making a small matching game in javascript. Why does the onclick listener stop working after the first successful attempt. How do I rectify this issue.
I am expecting the listener to be attached to the last child element of the div with id "leftSide" even after I refresh all nodes by removing old nodes first.
<!DOCTYPE html>
<html>
<head>
<title>Matching Game</title>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
</style>
</head>
<body>
<h2>Matching Game</h2>
<p>Click on the extra smile on the left</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
<script>
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
function generateFaces() {
for (var i=0; i<=numberOfFaces; i++) {
new_img = document.createElement("img");
new_img.src="smile.png";
new_img.style.top=String(Math.floor(Math.random()*400))+"px";
new_img.style.left=String(Math.floor(Math.random()*400))+"px";
theLeftSide.appendChild(new_img);
}
// Clone all images to right side
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
}
generateFaces()
var theBody = document.getElementsByTagName("body")[0];
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
theLeftSide.lastChild.onclick = function nextLevel(event) {
// remove child nodes
while (theLeftSide.firstChild) {
theLeftSide.removeChild(theLeftSide.firstChild);
}
while (theRightSide.firstChild) {
theRightSide.removeChild(theRightSide.firstChild);
}
// new nodes
event.stopPropagation();
numberOfFaces += 5;
generateFaces();
};
</script>
</body>
</html>
The problem is when you attach an event handler to an element, when that element is destroyed, the event is gone too (when the GC cleans). The theLeftSide.lastChild doesn't creates a reference to whatever last child element of theLeftSide is. It creates a reference to the current last child.
You must change the place you add the event handler to inside your generateFaces function, so everytime you change the theLeftSide children, you get again the last child, and add the event.
Take a look at the example below:
<!DOCTYPE html>
<html>
<head>
<title>Matching Game</title>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
</style>
</head>
<body>
<h2>Matching Game</h2>
<p>Click on the extra smile on the left</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
<script>
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
function generateFaces() {
for (var i = 0; i <= numberOfFaces; i++) {
new_img = document.createElement("img");
new_img.src = "http://www.webgranth.com/wp-content/uploads/2012/03/smile.png";
new_img.style.top = String(Math.floor(Math.random() * 400)) + "px";
new_img.style.left = String(Math.floor(Math.random() * 400)) + "px";
theLeftSide.appendChild(new_img);
}
// Clone all images to right side
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
theLeftSide.lastChild.onclick = nextLevel;
}
generateFaces()
var theBody = document.getElementsByTagName("body")[0];
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
function nextLevel(event) {
// remove child nodes
while (theLeftSide.firstChild) {
theLeftSide.removeChild(theLeftSide.firstChild);
}
while (theRightSide.firstChild) {
theRightSide.removeChild(theRightSide.firstChild);
}
// new nodes
event.stopPropagation();
numberOfFaces += 5;
generateFaces();
};
</script>
</body>
</html>
Note: I've simpled changed the theLeftSide.lastChild.onclick = function nextLevel(event) {, to a simple function declaration: function nextLevel(event) {, and then added the event handler inside the generateFaces function: theLeftSide.lastChild.onclick = nextLevel;.
you could try something like this:
<!DOCTYPE html>
<html>
<head>
<title>Matching Game</title>
<style>
img {
position: absolute;
}
div {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
</style>
</head>
<body>
<h2>Matching Game</h2>
<p>Click on the extra smile on the left</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
<script>
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
var clickLastChild = function clickLastChild() {
// remove child nodes
theLeftSide.lastChild.onclick = function (event) {
while (theLeftSide.firstChild) {
theLeftSide.removeChild(theLeftSide.firstChild);
}
while (theRightSide.firstChild) {
theRightSide.removeChild(theRightSide.firstChild);
}
// new nodes
event.stopPropagation();
numberOfFaces += 5;
generateFaces();
};
};
function generateFaces() {
for (var i = 0; i <= numberOfFaces; i++) {
new_img = document.createElement("img");
new_img.src = "smile.png";
new_img.style.top = String(Math.floor(Math.random() * 400)) + "px";
new_img.style.left = String(Math.floor(Math.random() * 400)) + "px";
theLeftSide.appendChild(new_img);
}
// Clone all images to right side
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
clickLastChild();
}
generateFaces();
var theBody = document.getElementsByTagName("body")[0];
theBody.onclick = function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
clickLastChild();
</script>
</body>
</html>
Here i made fully working jsfiddle
You have to call generateFaces() from game over scenario also.
And yes as #epascarello mentioned, you are losing click events as you are setting them to null.
Because you set the onclick to false
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
when you click the tbody.

I need to stop theBox

Hey guys I need to stop theBox when it moves out of the screeen (500x500)
I dont know how to anyhelp?
<style>
#box { position: absolute; top: 0; left: 0; background-color: green; }
</style>
<script>
onload = function() {
var theBox = document.getElementById("box");
function animate() {
if ("theBox")
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
}
setInterval(animate,100);
}
</script>
</head>
<body>
<div id="box">The box</div>
</body>
Just add a check to see if the next move will take the box up to or over 500. Also, I've added a call to clearInterval() when the box stops, to stop the timer.
onload = function() {
var timer;
var theBox = document.getElementById("box");
function animate() {
if(theBox.offsetLeft+5 < 500 && theBox.offsetTop+5 < 500){
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
} else {
clearInterval(timer);
}
}
timer = setInterval(animate,100);
}
I have added and if statement to check if the height of the page is higher than the offset top of the box:
onload = function() {
var theBox = document.getElementById("box");
function animate() {
if ("theBox")
if(window.innerHeight > (theBox.offsetTop+25)){
console.log(theBox.offsetTop+5)
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
}
}
setInterval(animate,100);
}
Code Pen

Adding a background image under a background color function

I have the three functions running on my interactive pet (change background, dimmer lights, mouse follow). I'm trying to add an image to the background of the body, but every time I try it gets pushed to the top and the dirty/clean tank function doesn't work. Could someone tell me how to change the color sections of the first function below to switch between images instead of color codes? I think that would solve the immediate problem. :/
CSS Code:
//change background color: dirty/clean tank
setTimeout(function dirty() { //sets background color to murky green
document.body.style.backgroundColor = ****"#CCCC99";** //would like this to be an image**
var btn = document.body.appendChild(document.createElement('button'));
btn.appendChild(document.createTextNode("Clean the tank!"));
document.body.style.marginTop = "-1000px";
btn.onclick = function clean() {
btn.parentNode.removeChild(btn);
document.body.style.backgroundColor = **"#CCFFFF";//would like this to be an image**
setTimeout(dirty,27000); //how long it takes to make the tank dirty
};
},500); //first loading of clear blue timeout
//dim the lights
var dimmed = 0;
function toggleLights()
{
var dimmer = document.getElementById("dimmer");
if(dimmed == 0) dimmed = 1;
else dimmed = 0;
if(dimmed == 1)
{
dimmer.style.opacity = 0.8;
dimmer.style.visibility = "visible";
}
if(dimmed == 0)
{
dimmer.style.opacity = 0.0;
dimmer.style.visibility = "hidden";
}
}
//fish moves on mouse hover
$(document).ready(function() {
$("#swim").mousemove(function (event) {
var fish = $("#fish1");
var position = fish.position();
var mousey = event.pageX;
if (position.left > mousey) {
$("#fish1").html("<img src='images/happy.png' />");
} else {
$("#fish1").html("<img src='images/happyback.png'/>");
}
$("#fish1").stop().animate({
left: event.pageX,
top: event.pageY
}, 300);
});
});
HTML Code:
<HTML>
<HEAD>
<TITLE>Untitled</TITLE>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"
</script>
<script type="text/javascript" src="pet.js"></script>
<script type="text/javascript" src="core.js"></script>
</HEAD>
<div id="table">
<div id="dimmer" onClick="toggleLights()"></div>
<a href="javascript:toggleLights();"><img src="images/table-lamp.png" height="380px"
alt="table lamp"></a>
</div>
<div id="swim">
<div id="fish1"><img src="images/happy.png"/></div>
</div>
</BODY>
</HTML>
Add a starting <body> tag in your HTML, and change element classes with javascript, instead of style properties. That way you have more control over the styling through your CSS file.
So you would do something like:
document.body.className = 'state1';
And in your CSS
.state1{
background-image: url(the/image.jpg);
}
and so on...

Categories