how to disable onclick function once it is less than another variable? - javascript

Hello everyone and thanks for any help in advance,
I have some functions already in place, first one adds 1% of the total money amount once every second. the second is onclick there is $100 added to the total original amount. The third is to minus $200 plus 10% of the 200 from the total amount, so every time it is clicked the minus amount goes up.
These functions are working on my local machine but I am unable to get them to work in a JSFIDDLE.
I want to disable the minus button once the total amount is less than the minus amount, and also enable it again once there is enough money in the total amount to use.
Here is my JS so far
setInterval(function () {
var moneyTotal = document.getElementById('money-total').innerHTML;
var perSec = (1 / 100) * moneyTotal;
var moneyNewTotal = (+moneyTotal) + (+perSec);
document.getElementById('money-total').innerHTML = (moneyNewTotal.toFixed(2));
document.getElementById('per-second').innerHTML = (perSec.toFixed(2));
}, 1000);
function add() {
var addAmount = 100;
var moneyTotal = document.getElementById('money-total').innerHTML;
var addTotal = (+addAmount) + (+moneyTotal);
document.getElementById('money-total').innerHTML = (addTotal.toFixed(2));
}
function minus() {
var cost = document.getElementById('cost').innerHTML;
var money = document.getElementById('money-total').innerHTML;
if (money > cost) {
var moneyNewTotal = (+money) - (+cost);
var newCost = (10 / 100) * cost;
var costTotal = (+newCost) + (+cost);
document.getElementById('cost').innerHTML = Math.ceil(costTotal);
document.getElementById('money-total').innerHTML = (moneyNewTotal.toFixed(2));
} else {
alert("Not enough money");
}
}
Any help would be greatly appreciated!

First, the Fiddle isn't working because you have it set to load your javascript onLoad which is wrapping your functions in a different scope and so they aren't available on the window. Changing it to load the javascript No wrap - in <head> (or <body>) will help it work.
Then you need to have something that is checking for the value and enabling disabling the minus button.
function checkTotal() {
var moneyTotal = +document.getElementById('money-total').innerHTML;
var cost = +document.getElementById('cost').innerHTML;
if (cost > moneyTotal) {
document.getElementById('minus').setAttribute('disabled', 'disabled');
} else {
document.getElementById('minus').removeAttribute('disabled');
}
}
Then you would need to call this at the end of the add, minus, and even the function you have defined in setInterval so that as money gets added it checks. This code only adds the disabled attribute to the button, so any styling would need to be handled either by the code or through CSS and setting/removing class names or something similar.
There are perhaps different ways to do this through data binding or using an event model as part of a framework, but those are a more substantial topic that can't really be covered in this answer.

Related

Conditional statement is not recognizing variable values

I am making a simple reaction time game for a final project.
We are using javascript to power the functions in the game, most of my code is in working order, but I have an if conditional statement that's giving me trouble.
Here's the code
function fireTime() {
setTimeout(ShotsFired, time);
function ShotsFired() {
fire.style.visibility = "visible";
createdTime = Date.now();
console.log(createdTime);
EnemyTime = Math.floor((Math.random() * 1000) + 400);
setTimeout(EnemyShoot, EnemyTime)
function EnemyShoot() {
console.log(EnemyTime);
gameplay();
}
function gameplay() {
reactionTime = -(createdTime - clickedTime);
var EnemyTime;
console.log(reactionTime);
if (reactionTime < EnemyTime) {
alert("Wow you beat him! Congrats!");
fire.style.visibility = "hidden";
clickedTime = 0;
createdTime = 0;
reactionTime = 0;
scavnumber++;
BGnumber++;
DesertBG.src = "images/Desert" + BGnumber + ".png";
scav.src = "images/scav" + scavnumber + ".png";
fireTime();
} else {
EndScreen.style.visibility = "visible";
}
}
This is not the entire code, just the function that should progress the game to the next level.
For whatever reason, even though reactionTime is less than EnemyTime, the EndScreen becomes visible.
Anyone know what could cause this?
Use floating point for your enemy time maths, i.e. 400.0 , else you are getting 0/1 seconds and not using milliseconds, and it is useing Math integer. Specifically cast your enemyTime as a float number, for the moment, if you print it it's probably an integer. its a MAJOR js coding detail that you will cost you hours of bughunting in the future if you think that 101/50 = 2.05, it isn't it equals 2, so divide by 50.0 and same with all second/ms tasks.
Use EnemyTime as a global variable for all scripts, at the moment, the code things you have a different function called EnemyTime in all scripts, the latter one has no value.
Use print to see when your else conditions work, specify a print in both an print the enemyTime value.
That's how you are supposed to resolve the issue, by printing the variables that are confusing.

how to create direct display randomly number

I want to ask, how to make this script directly display the total of numbers on my blog post without clicked, And will change if browser is refreshed.
` http://jsfiddle.net/BenedictLewis/xmPgR/
There the problem is, your getNumber() function is executing only after click. There is no way it is not added to on load part.
One simple way is call the function getNumbers() after declaration as i did:
var link = document.getElementById('getNumber'); // Gets the link
link.onclick = getNumber; // Runs the function on click
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
$('#myNumber').html(randomnumber); // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
getNumber(); // here i called the method, it runs on load of the script
//and works as you wanted

JavaScript and Array's

EDIT I originally posted this with my version of the J.S but it's so far off no one can even help so i'm starting over. Here is the pseudocode i have done that needs to be translated into a Javascript program. Any help is appreciated!
I am a beginning programmer i understand this code will have multiple errors, that's why i am here. Array's and loops have given me much trouble while trying to learn them and especially with formatting them in JavaScript. The things i know are incorrect or still need i commented out i still need them, i also know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated.
Module main()
//Declare local variables
Declare endProgram = “no”
While endProgram == “no”
Declare Real notGreenCost[12]
Declare Real goneGreenCost[12]
Declare Real savings[12]
Declare String months[12] = “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”
//function calls
getNotGreen(notGreenCost, months)
getGoneGreen(goneGreenCost, months)
energySaved(notGreenCost, goneGreenCosts, savings)
displayInfo(notGreenCost, goneGreenCosts, savings, months)
Display “Do you want to end the program? Yes or no”
Input endProgram
End While
End Module
Module getNotGreen(Real notGreenCost[], String months[])
Set counter = 0
While counter < 12
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End While
End Module
Module getGoneGreen(Real goneGreenCost[], String months[])
Set counter = 0
While counter < 12
Display “Enter GONE GREEN energy costs for”, months[counter]
Input goneGreenCosts[counter]
Set counter = counter + 1
End While
End Module
Module energySaved(Real notGreenCost[], Real goneGreenCost[], Real savings[])
Set counter = 0
While counter < 12
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo(Real notGreenCost[], Real goneGreenCost[], Real savings[], String months[])
Set counter = 0
While counter < 12
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
A few notes:
Currently the program creates a few variables and functions that
don't seem to interact
Most of the edits below are not optimal - there are parts that
could be done by much simpler means (i.e. counter++) - But thats
for you to learn =P
I made quite a few assumptions of what you wanted the program to
do, they might be wrong, they might be right
var notGreenCost = []; //Array lengths don't need to be specified
var goneGreenCost = [];
var savings = [];
var months = ["January", "Feburary", "March", "April", "May", "June"];
//A boolean value (true | false) would suit this better as opposed to "yes"/ "no"
var endProgram = false;
var option = 0;
/* You dont need main functions in javascript
* migrated everything to be global :/
* Delete:
function main(){
// Move this (made it global): var endProgram = "no";
}
*/
// I don't think this is meant to be initMonths..
// Maybe something like getOptions?
function /*initMonths*/getOptions(){
while (endProgram == false){ //lowercase while
//Because prompt would block everything else until it gets input
//we probably want to move the prompt to be after the alerts
alert("options:"); //Clarity
alert("1 to enter data");
alert("2 to display data");
alert("3 to write data to a file");
alert("4 to read data from a file");
//Alter global "option" to take the value of the prompt
option = prompt("What would you like to do? Type:");
//} //I assume you want the rest of the code in this while loop - otherwise it will loop forever
// Delete this bracket (its unmatched): {
// Delete return statement as it will stop the function return option;
// Delete this bracket (its unmatched): }
//Create a variable to take the value of prompt (this should be outside the while loop) but it seem clearer for explanation purposes to be here
var toEnd;
toEnd = prompt("Do you want to end the program (enter yes or no)");
// Javascript uses != for "not equal to" and && for "AND"
while (toEnd != "no" && toEnd != "yes") {
toEnd = prompt("Please enter a value of yes or no");
}
//I think you want to assign the value of toEnd to endProgram
// Note the the below is not the only/best way to do it
if(toEnd == "no") {
endProgram = false;
} else if(toEnd == "yes") {
endProgram = true;
}
// While use brackets not End s
// End While
// End While
}//End while loop here
}
Javascript in a browser cannot alter files - writeToFile, readFromFile have all been removed
I believe you want months to be global, if it is then initMonths is unnecessary
getNotGreen:
function getNotGreen(){
//You don't need to specify types in Javascript
/*Integer*/ var counter = 0
while (counter < 6){ //lowercase while
//I'm assuming you want to combine the values of "Enter NOT GREEN energy costs for" and months[counter] - This is done by using the + sign
//Im also assuming you want to read the value into notGreenCost
//.push adds a value to a array
notGreenCost.push(prompt("Enter NOT GREEN energy costs for" + months[counter]))
//Returning here makes the rest of the function redundant
//}
//return notGreenCost[counter];
//}
//Javascript does not use Set
// Note that below is not the only/best way to do it
/*Set*/ counter = counter + 1
} //End the while loop here
}
getGoneGreen:
function getGoneGreen(){
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
//I'm assuming you want to combine the values of "Enter NOT GREEN energy costs for" and months[counter] - This is done by using the + sign
//Im also assuming you want to read the value into notGreenCost
//.push adds a value to a array
goneGreenCost.push(prompt("Enter GONE GREEN energy costs for" + months[counter]));
//See above (getNotGreen)
//}
//return goneGreenCost[counter];
/*Set*/ counter = counter + 1;
}//End while loop here
}
energySaved:
function energySaved(){
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
savings[counter] = notGreenCost[counter] - goneGreenCost[counter]
counter = counter + 1;
}
} //I assume you want to end energySaved here?
displayInfo:
function displayInfo(){
//Alert produced individual boxes, i assume you want the following in a single window?
// "\n" is a line break
alert("SAVINGS NOT GREEN GONE GREEN MONTH\n"+
"_________________________________________________\n");
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
alert( "$" + savings[counter] + "$" + notGreenCost[counter] + "$" + goneGreenCost[counter] + "" + months[counter]);
counter = counter + 1;
}
} //I assume you want to end displayInfo here?

Substract value from variable JS

I've making a game where you should sell your product.
But for some reason my function to substract that amount from the produced product, is not working, i can for some reason produce unlimited money. I've tried to check in the console what the value is after substrackting, but it is unchanged.
var x = document.getElementById.bind(document);
x('sell').onclick = function() {
if (dipped_cookie < 1) {
return false;
} else {
dipped_cookie -= sell;
console.log(dipped_cookie);
bank += sell;
}
Hope you can help. Thanks in advance
If dipped_cookie, sell and bank aren't global variables, they are not defined. And when you try to add some javascript variable which is not defined, the value become NaN

How to add multiples of a number and overwrite previous entry using js timing?

I am trying to create a function that continuously adds the same number to itself. Or simply displays multiples of one number every so many seconds with the setInterval method.
For now, let's just say I want to display multiples of ten.
I know how to get a regular while loop to simply display multiples of ten in a row, but what I want to do here is continually replace the previous text every time the function is called. I am trying to create a game and this is going to be the experience calculator. So it needs to display the total experience earned over the given time.
I was trying something along the lines of this:
window.setInterval(
function writeExp ()
{
var j;
while (rounded > 0)
{
var i = w*10;
var j = j + i;
}
document.getElementByID("exp").innerHTML=j;
}, experience)
This seems logical enough to me, but obviously something is wrong, as it does not work. I have tried googling various things like how to sum numbers in javascript or continuously sum, among others, but it is somewhat difficult to word to get it more centered to my needs. So this is the best way to get my questions answered.
There are lot of undefineds in your code, but general example would be
var interval = 1000,
result = 0,
elem = document.getElementByID("exp");
window.setInterval(function () {
result *= 10;
elem.innerHTML = result;
}, interval);
or without global variables
var interval = 1000,
multiply = function (elem) {
var result = 0;
return function () {
result *= 10;
elem.innerHTML = result;
}
};
window.setInterval(multiply(document.getElementByID("exp")), interval);

Categories

Resources