Increment & Decrement not working as intended in Javascript - javascript

The unexpected behavior I'm getting is when clicking the donate or undonate button. It takes 2 clicks initially for the tracker to display the incremented or decremented number despite the color change happening immediately. Once it does change the number on the second click, the 3rd click and on using the same button will work normally to increment or decrement.
In addition to that, if you switch the button you're clicking to the other, it still performs the previous action first.Hopefully this explanation of the issue makes sense. Appreciate any direction that can be given as I am still new!
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href='style.css' />
<title>Front-End Portfolio Project</title>
</head>
<body>
<h1>Donate Food 2 Me</h1>
<p id="container"></p>
<p id='caption'>food quantity</p>
<button id="donate">Donate</button>
<button id="undonate">Un-Donate</button>
<script type="text/javascript" src='main.js'></script>
</body>
</html>
JS:
const donateButton = document.getElementById("donate");
const unDonateButton = document.getElementById("undonate");
const tracker = document.getElementById("container");
var i = 0;
tracker.innerHTML = i;
donate = function(){
donateButton.style.backgroundColor = 'red';
tracker.innerHTML = i++;
}
undonate = function(){
unDonateButton.style.backgroundColor = 'blue';
tracker.innerHTML = i--;
}
donateButton.addEventListener("click", donate);
unDonateButton.addEventListener("click", undonate);

The only mistake you made is ignoring the difference between i++ and ++i (i-- and --i).
Change your code as below (You can see the result here):
donate = function(){
donateButton.style.backgroundColor = 'red';
tracker.innerHTML = ++i;
}
undonate = function(){
if (i > 0) {
unDonateButton.style.backgroundColor = 'blue';
tracker.innerHTML = --i;
}
}

Related

How to do an action when a variable hits a specific number javascript

So basically I have done this code down bellow and I am trying to have a button that adds 1 to a variable and when that variable hits the specific number it plays an action. My final goal is to make it so when the variable hits the specific number it redirects to another page. I have tried for way too long and my friends don't know the solution either.
<!DOCTYPE html>
<head> </head>
<!DOCTYPE html>
<html>
<head>
<title> click tester </title>
<Meta charset="utf-8">
</head>
<body>
<script>
var theClicks = 1;
const win = 25;
if(theClicks >= win) {
alert('over 25');
}
</script>
<button onclick=theClicks++;>Button that adds1 to variable</button>
</body>
</html>
<button onclick=theClicks++;>Button that adds1 to variable</button>
Just increments the variable. To expand that you could add more actions in the button onclick event, but it's much better to just put it all in a function you can call.
<script>
var theClicks = 1;
const win = 25;
function doThing() {
if (++theClicks >= win) {
alert('over 25');
}
}
</script>
<button onclick='doThing()'>Button that adds1 to variable</button>
You could take an approach like below. Basically create a function that keeps track of a counter variable (i.e., i). Next add a click event listener to the button and increment the counter on each click. When the counter reaches 25 then do some action (I made it only needed to be clicked 3 times in the code below for demo convenience) .
For example:
// Reference to the DOM elements
const countEl = document.querySelector('#count-el');
const buttonEl = document.querySelector('button');
// Init a counter variable and return a function that increments it
const increment = (() => {
let i = 1;
return () => i++;
})();
// The click event listener
buttonEl.addEventListener('click', () => {
// Increment the count and update the UI if current click count is 3
if (increment() === 3) {
countEl.textContent = 'Do action now!';
}
});
<span id="count-el"></span>
<br />
<button>Click 3 times to do action</button>

localStorage not working to "save" game

Good day!
Complete JS noob here. I was following this tutorial: http://dhmstark.co.uk/incrementals-part-2.html regarding saving and loading the game. However, it is not working at all. I was hoping you fine folks might be able to easily tell me the issue with the code. There are no errors coming up on the browser console at all. But, when I re-load the page, it is not loading the "saved" data. I have tried putting the load() function within the js file itself, as well as including in the HTML header. I have also tried calling the load() function with a window.onload within the script itself.
Please help.
HTML
<!DOCTYPE HTML>
<head>
<title> Game </title>
<link rel="stylesheet" type="text/css" href="interface.css" />
<script type="text/javascript">
function load() {
var savegame = JSON.parse(localStorage.getItem("save"));
if (typeof savegame.clicks !== "undefined") clicks = savegame.clicks;
}
</script>
</head>
<body onload="load()">
<button onClick="increment(1)"> Click </button>
<span id="clicks"></span><br /><br />
<button onClick="buyThing()"> Buy Thing </button><br />
Things: <span id="things">0</span><br />
Next Thing Cost: <span id="thingCost">10</span>
<script type="text/javascript" src="main.js"></script>
</body>
JS
//click tracker
var clicks = 0;
function increment(number){
clicks = clicks + number;
document.getElementById("clicks").innerHTML = clicks;
};
//cursor
var things = 0;
function buyThing(){
var thingCost = Math.floor(10 * Math.pow(1.1, things)); //works out cost of this cursor
if(clicks >= thingCost){ //check that player has enough clicks to afford cursor
things = things + 1; //increase number of cursors
clicks = clicks - thingCost; //remove clicks spent
document.getElementById('things').innerHTML = things; //update the number of cursors for the user
document.getElementById('clicks').innerHTML = clicks; //update the number of clicks for the user
};
var nextCost = Math.floor(10 * Math.pow(1.1,things)); //works out the cost of the next cursor
document.getElementById('thingCost').innerHTML = nextCost; //updates the cursor cost for user
};
var save = {
clicks: clicks,
things: things,
}
//loop
window.setInterval(function(){
increment(things);
localStorage.setItem("save",JSON.stringify(save));
}, 1000);
Your save object will be declared and defined only once and never be changed, so you will be saving over and over again the first initial value of the progress, you should save a newly object on each interval:
window.setInterval(function(){
increment(things);
localStorage.setItem("save",JSON.stringify({clicks: clicks, things: things}));
}, 1000);
You are getting a reference issue. The memory addresses of clicks and save.clicks are not pointing to the same thing, since it's a primitive number.
Putting all your game data into a single object will help reduce the global namespace pollution as well.
<!DOCTYPE HTML>
<head>
<title> Game </title>
<link rel="stylesheet" type="text/css" href="interface.css" />
<script type="text/javascript">
function load() {
return JSON.parse(localStorage.getItem("game")) || {
clicks: 0,
things: 0
};
}
</script>
</head>
<body onload="load()">
<button onClick="increment(1)"> Click </button>
<span id="clicks"></span><br /><br />
<button onClick="buyThing()"> Buy Thing </button><br />
Things: <span id="things">0</span><br />
Next Thing Cost: <span id="thingCost">10</span>
<script type="text/javascript" src="main.js"></script>
JS
//click tracker
var game = load();
function increment(number){
game.clicks += number;
document.getElementById("clicks").innerHTML = game.clicks;
};
//cursor
function buyThing(){
var thingCost = Math.floor(10 * Math.pow(1.1, game.things)); //works out cost of this cursor
if(game.clicks >= thingCost){ //check that player has enough clicks to afford cursor
game.things++; //increase number of cursors
game.clicks -= thingCost; //remove clicks spent
document.getElementById('things').innerHTML = game.things; //update the number of cursors for the user
document.getElementById('clicks').innerHTML = game.clicks; //update the number of clicks for the user
};
var nextCost = Math.floor(10 * Math.pow(1.1,game.things)); //works out the cost of the next cursor
document.getElementById('thingCost').innerHTML = nextCost; //updates the cursor cost for user
};
//loop
window.setInterval(function(){
increment(game.things);
localStorage.setItem("game",JSON.stringify(game));
}, 1000);

Show changes from an currently executing for loop

I could need some help, or maybe just an answer. Is there a way to show changes made by aa js within an executing for loop ? I know there is a way with setInterval, but I have an example with a greater progress where I need it to progress the problem with a for loop. So here is my try:
<!doctype html>
<html>
<head>
<title>life change test</title>
<meta charset="UTF-8">
</head>
<body>
<div id="wrapper">
</div>
<script type="text/javascript">
var el = document.getElementById("wrapper");
/*var i = 0;
var counter = setInterval(function(){
el.innerHTML = i;
i++;
if(i == 18000){
clearInterval(counter);
}
}, 10);*/
for (var i = 400000; i >= 0; i--) {
el.innerHTML = i;
};
</script>
</body>
</html>
My Firefox just freezes until it is completely done, and than displays the result. Is there a chance to actually see the progress ?

one button two if statements for a css div in javascript

If I use two buttons it works fine now I wonder if I could use just one and how, this is the code for two buttons however I want to use only one button to execute the code that changes the style of the div, for instance the buttons code that I wrote is:
<title></title>
<style>#ok{width:100px;height:100px;background-color:black;}</style>
</head>
<body>
<div id="ok">ok</div>
<button id="a">on</button>
<button id="b">off</button>
<script>
var a=document.querySelector("#a");
var b=document.getElementById("ok");
a.addEventListener("click",k,false);
var c=document.querySelector("#b");
c.addEventListener("click",g,false);
function k(){
b.style.backgroundColor="yellow";
};
function g(){
b.style.backgroundColor="black";
};
</script>
I think what do you want to do is:
document.querySelector("#a").addEventListener("click", k, false);
function k() {
var a = document.querySelector("#a");
var ok = document.getElementById("ok");
if(ok.style.backgroundColor=="yellow"){
a.innerHTML = "on";
ok.style.backgroundColor = "black";
}
else{
a.innerHTML = "off";
ok.style.backgroundColor = "yellow";
}
};
This your working DEMO.

new mail counter javascript

I am having some major problems with a javascript app I'm working on. I want my window to open to a closed envelope and then after five seconds to change to an open envelope with a little 1 counter in the corner of it. I want the counter to continue to move up every five seconds unless the envelope is clicked. If clicked I want the count to start over. So far I have only gotten my closed envelope showing up. I'm new and have no idea what I am doing wrong so any help would be awesome!
My html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="mail.js"></script>
</head>
<body>
<img id"closed" src="closed.png" onclick="resetTimer()">
<span id="counter"></span>
</body>
</html>
And my JavaScript:
window.onload = function(){
var counter = 0;
var timer = setInterval(
function(){
counter++;
document.getElementById("demo").firstChild.nodeValue = counter;
},
5000
);
function openEnvelope(){
var img = document.getElementById("picture");
if (counter > 1){
img.src = "open.png"
}
}
open = setTimeout("open()", 1000);
function resetTimer(){
clearInterval(timer);
}
}
You need to increment your counter and set the counter span to have that value :
var counter = 0;
//Create your timer (setTimeout will only run once, setInterval will start again once run.
//1000 = 1 second
var timer = setInterval(openEnvelope, 1000);
function openEnvelope() {
var img = document.getElementById("picture");
var counterSpan = document.getElementById("counter");
if (counter > 1) {
img.src = "open.png"
counterSpan.innerHTML = counter;
}
//Add 1 to Counter
counter++;
}
function resetTimer() {
clearInterval(timer);
counter = 0;
}
This will run your openEnvelope function every second, and if the counter value is more than 1 it will set the Img Source to be open.png and the counter span to have the counters value. On the click of the Envelope it will clear the timer and reset the counter.
And your HTML will become :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="mail.js"></script>
</head>
<body>
<img id"picture" src="closed.png" onclick="resetTimer()">
<span id="counter"></span>
</body>
</html>
Here is a working JSFiddle for your problem, try creating a blank page and copying the HTML straight into the <body> tag and the Javascript into <script></script> tags in the <head> of your page.

Categories