I am currently trying to have an if statement run after soulamount is 10. However, the if statement only works when soulamount is 0. This is due to soulamount being set at 0 to begin with. However, when the user clicks a button, the soulamount goes up. I’m assuming the if statement is not working as intended due to it running as soon as the page loads. So, how do I go about running the if statement when soulamount reaches 10?
let soulAmount = 0;
let soulAddition = 1;
let grabSps = document.querySelector(".sps").innerHTML;
let sps = parseInt(grabSps);
let upgradecost1 = 10;
function getSoul() {
soulAmount += soulAddition;
document.querySelector(".souls_amount").innerHTML = soulAmount;
return soulAmount;
}
function upgrade1() {
if (soulAmount >= upgradecost1) {
sps += 1;
soulAmount -= upgradecost1;
document.querySelector(".souls_amount").innerHTML = soulAmount;
document.querySelector(".sps").innerHTML = sps;
return soulAmount;
} else {
alert("You do not have enough souls!")
}
}
window.setInterval(function() {
document.querySelector(".souls_amount").innerHTML = soulAmount += sps;
}, 1000);
if(soulAmount == 10) {
console.log(soulAmount)
}
function achievement1() {
alert("Achievement Unlocked. You've collected 100 Souls!")
document.getElementById("collect100").style.display = "block"
}
I have tried searching for results but got nowhere. Someplace stated to not use an assignment operator and use "==" or "===" instead, but that didn’t help. In the end, I realised the problem, I just dont know how to overcome it.
>Solution :
I created a function called validateSoul that I added anywhere your soul variable is being modified. This way anytime the value of soul is changed, you can verify its value and do what is needed.
let soulAmount = 0;
let soulAddition = 1;
let grabSps = document.querySelector(".sps").innerHTML;
let sps = parseInt(grabSps);
let upgradecost1 = 10;
function validateSoul(){
if(soulAmount === 10){
console.log("!!!")
}
}
function getSoul() {
soulAmount += soulAddition;
validateSoul();
document.querySelector(".souls_amount").innerHTML = soulAmount;
return soulAmount;
}
function upgrade1() {
if (soulAmount >= upgradecost1) {
sps += 1;
soulAmount -= upgradecost1;
validateSoul();
document.querySelector(".souls_amount").innerHTML = soulAmount;
document.querySelector(".sps").innerHTML = sps;
return soulAmount;
} else {
alert("You do not have enough souls!")
}
}
window.setInterval(function() {
document.querySelector(".souls_amount").innerHTML = soulAmount += sps;
validateSoul();
}, 1000);
function achievement1() {
alert("Achievement Unlocked. You've collected 100 Souls!")
document.getElementById("collect100").style.display = "block"
}