I'm still pretty new to JavaScript and need to be pointed in the right direction on a tiny project that is just for practice.
Very sorry if I'm not posting incorrectly, this is my first post on Stack Overflow and any help is appreciated.
I've tried accomplishing my goal a few different ways and haven't gotten there.
attack.addEventListener("click", function(){
hit();
});
function hit(){
if (bossHealth.textContent > 0 && playerFocus.textContent >=2) {
playerFocus.textContent -= 2;
bossHealth.textContent -= 3;
console.log("attack");
}
else if (bossHealth.textContent >= 0 && playerFocus.textContent < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
};
strong.addEventListener("click", function(){
bigHit();
});
function bigHit(){
if(bossHealth.textContent > 0 && playerFocus.textContent >= 5){
playerFocus.textContent -= 6;
bossHealth.textContent -= 6;
console.log("strong attack");
}
else if (playerFocus <5){
alert("Strong attack costs 5 focus, if you do not have enough focus try regenerating for a turn");
}
else (bossHealth.textContent <= 0){
bossHealth.textContent = "Dead";
alert("You've killed the bad guy and saved the world!!!");
}
};
easy.addEventListener("click", function(){
reset();
});
function reset(){
playerHealth.textContent = 10;
playerFocus.textContent = 10;
bossHealth.textContent = 10;
};
hard.addEventListener("click", function(){
hardMode();
});
function hardMode(){
playerHealth.textContent = 10;
playerFocus.textContent = 10;
bossHealth.textContent = 15;
};
With function hit I don't get the alert in my else if statement
with function bigHit I also don't get my alert for the else if statement and neither part of the else statement works.
also subtraction works in my functions, but when trying to add another function that uses addition in the same way it adds the number to the end of the string instead of performing math
You really shouldn't depend on what is in the DOM for logic. You should try with local variables then update the DOM based on those variables.
var boss = {}
var player = {}
function reset(){
player.health = 10;
player.focus = 10;
boss.health = 10;
update()
};
function hit(){
if (boss.health > 0 && player.focus >=2) {
player.focus -= 2;
boss.health -= 3;
console.log("attack");
} else if (boss.health > 0 && player.focus < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
update()
}
function update() {
playerFocus.textContent = player.focus
playerHealth.textContent = player.health
bossHealth.textContent = boss.health
}
Your issue is caused by textContent automatically turning your numbers into strings, by managing the data using your own variables this doesn't affect your code's logic.
Alternatively you could parse the strings as numbers using new Number(playerFocus.textContent), parseFloat(playerFocus.textContent), or +playerFocus.textContent but your code will become very hard to read very quickly.
Hope this enough to help you to make more edits to your code.
It looks like your playerFocus variable is a DOM node? Based on that assumption, your condition is missing a check for its textContent:
if (bossHealth.textContent > 0 && playerFocus.textContent >= 5){
// ...
}
else if (playerFocus.textContent <5){
// ...
In JavaScript, else blocks cannot have conditions, so if you want to conditionally check whether bossHealth.textContent <= 0 at the end of your bigHit function, you will need to change it to an else if (bossHealth.textContent <= 0) { ... } block instead.
I'm adding on to #LoganMurphy's comment and my own. In order to use the value of bossHealth it needs to be an integer. Change your code to look something like this:
function hit(){
if (parseInt(bossHealth.textContent) > 0 && parseInt(playerFocus.textContent) >=2) {
playerFocus.textContent -= 2;
bossHealth.textContent -= 3;
console.log("attack");
}
else if (parseInt(bossHealth.textContent) >= 0 && parseInt(playerFocus.textContent) < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
};
https://www.w3schools.com/jsref/jsref_parseint.asp
Related
Im trying to make a simple clicker game (im pretty new to coding in javascript) but the player can buy things even if they dont have enough, so i tried to do this
function clickpowup() {
if(click += 50) {
clickpower += 5;
click += -50;
}
if(click !== 50) {
alert("Not enough cookies")
}
This is how my variables are laid out above the text
var click = 0;
var clickpower=1;
function clickpowup() {
if(click += 50) { ///here the code is wrong? if(click <= 50) you want?
clickpower += 5;
click += -50;
}
if(click !== 50) {
alert("Not enough cookies")
}
The if the condition seems wrong. if(click <= 50) are you looking for something like this?
If I'm reading your code right and understanding it... did you mean += to be "greater than or equal to?" If so, that's >= not +=. Also if (click !== 50) would mean "if click is not 50." 51 is not 50, but is "enough cookies" so that should be if (click <= 50), right?
The if condition you have coded is not correct(if(click += 50)).The if condition should return either true or false. It cannot interpret the output of this addition operation.
END NOTE:
Please try to explain your code in a better way
Im trying to practice loops in Javascript. I have a program that asks for the temperatures for the last week then works out its average and prints a text depending on the results. I have added into it to return an error if the number entered is not between -30 and 40 and stop the loop. This works ok apart from I still get the other text based on the average. I understand that using break like I am will still continue the rest of the code after the loop which is why Im getting the other text still. I am just starting out in the basics so it should be as simple as possible. How can I do it so as not to get the other text, what should I be using instead?
<meta charset="UTF-8">
<title>Lämpötilat</title>
<script language="JavaScript">
var lampotila=0;
var i;
for (var i = 0; i < 7; i++) {
lampotila = Number(prompt("Enter the temperatures for the last 7 days"));
if(lampotila <-31 || lampotila > 40) {
document.write ("ERROR: You must enter a temperature between -30° and 40°");
{break;}
}
}
yht = yht + lampotila;
k = yht / 7
ki = k.toFixed(2);
if (ki < -10) {
document.write ("Kylmää talvisäätä!");// cold winter weather
}
else if (ki <0 && ki> -10) {
document.write ("Hyvä hiihtosää!");// good skiing weather
}
else if (ki >0 && ki <10) {
document.write ("Kevät tulossa!");// spring is coming
}
else {
document.write("T-paita vois riittää!");// t- shirt should be enough
}
</script>
Increasing the indentation may help making the code more readable and easier to detect errors and bugs.
From http://www.w3schools.com/js/js_break.asp we know that break; lets us get out of a loop. So, after the break no more iterations will be made inside that loop and the computer will continue executing what is after that loop.
Your second part of the code is outside the loop, so doing break in the loop will not affect the rest. You could have a variable that indicates if an error was found while inputting data. If so, then don't execute the rest of the code.
Something like this:
var lampotila=0;
// var i; <= You don't need this if you `var i=0` inside the foor loop.
// Also, you don't use i outside the loop so there is no need
// to have it declared in the global scope.
var error = false; // <== THIS LINE NEW
for(var i=0; i<7;i++){
lampotila=Number(prompt("Enter the temperatures for the last 7 days"));
if(lampotila <-31 || lampotila > 40) {
document.write ("ERROR: You must enter a temperature between -30° and 40°");
error = true; // <== THIS LINE NEW
break;
}
}
if (!error) { // <== THIS LINE NEW
yht=yht+lampotila;
k=yht/7
ki=k.toFixed (2);
if (ki < -10){
document.write ("Kylmää talvisäätä!");// cold winter weather
}
else if(ki <0 && ki> -10) {
document.write ("Hyvä hiihtosää!");// good skiing weather
}
else if (ki >0 && ki <10) {
document.write ("Kevät tulossa!");// spring is coming
}
else {
document.write("T-paita vois riittää!");// t- shirt should be enough
}
} // <== THIS LINE NEW
You can decrease i value before break. So, user must enter true temperature value.
if(lampotila <-31 || lampotila > 40) {
document.write ("ERROR: You must enter a temperature between -30° and 40°");
i = i - 1;
continue;
}}
You have a syntax error in the below line:
{break;}
Try this:
for (var i = 0; i < 7; i++) {
lampotila = Number(prompt("Enter the temperatures for the last 7 days"));
if (lampotila < -31 || lampotila > 40) {
document.write("ERROR: You must enter a temperature between -30° and 40°");
break;
}
yht = yht + lampotila;
k = yht / 7
ki = k.toFixed(2);
if (ki < -10) {
document.write("Kylmää talvisäätä!"); // cold winter weather
} else if (ki < 0 && ki > -10) {
document.write("Hyvä hiihtosää!"); // good skiing weather
} else if (ki > 0 && ki < 10) {
document.write("Kevät tulossa!"); // spring is coming
} else {
document.write("T-paita vois riittää!"); // t- shirt should be enough
}
}
I have an ad I'm working on that displays user inputs from another page but since these inputs can be large numbers, I need to apply JS to format them to be $1K instead of $1000, $1M instead of $1,000,000 and so on. I've tried a few scripts that work in the console but aren't connecting with the HTML that has a value (that I input just to test the JS). I need to make sure this will work on whatever's inside the span tag since on the actual ad there will be a dynamic value that is pulling in whatever the user's input was. I'm pretty sure the issue is in regards to how I'm calling the value inside the first span with the #old id/ .current class, but I've tried several iterations of how to target that value and am getting further from the fix.
I have two JS scripts that are commented out currently, Attempt 1 and Attempt 2 and I'm wondering if it is in relation to the variable that is being defined before the function in Attempt 2 or if there's something missing at the end of either to have the script applied to the value I'm targeting.
Here's the codepen I have so far: http://codepen.io/linzgroves/pen/KgGPGX
If anyone has suggestions on what to adjust here, that'd be super helpful. Thank you!
P.S. I have looked at (and tried) several of the similar questions that have been asked about JS number formatting (such as this) but my issue seems to be more a matter of me incorrectly targeting the value within the span tag and not with the JS itself. However, if there is a similar question related to targeting elements correctly, I'd be happy to pointed towards that as well!
Also, let me know if there's additional information I need to provide.
Thanks!
<div id="container">
<div id="inner">
<div id="message_container">
<div id="roi-headline">
<h2>Cool Header</h2>
<h1>An even cooler headline</h1>
</div>
<div id="roi-values">
<div id="roi-value-1">
<div id="roi-value-1-graph" style="width:75%;">
<em>from</em> <sup>$</sup>
<span id="old" class="current">
100000
</span>
</div>
</div>
<div id="roi-value-2">
<div id="roi-value-2-graph" style="width:100%;">
<em>to</em>
<span><sup>$</sup>15<sup>K</sup></span>
</div>
</div>
</div>
<div id="button">Learn More</div>
</div>
</div>
</div>
Edit: Updated the following var to include .innerText
/* Attempt 1 */
var num = document.getElementById("old").innerText;
function nFormatter(num) {
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return num;
};
/* Attempt 2 */
var value = "span.current";
function prettifyNumber(value) {
var thousand = 1000;
var million = 1000000;
var billion = 1000000000;
var trillion = 1000000000000;
if (value < thousand) {
return String(value);
}
if (value >= thousand && value <= 1000000) {
return Math.round(value/thousand) + 'k';
}
if (value >= million && value <= billion) {
return Math.round(value/million) + 'M';
}
if (value >= billion && value <= trillion) {
return Math.round(value/billion) + 'B';
}
else {
return Math.round(value/trillion) + 'T';
}
};
Your functions work just fine - if you want the changes reflected in the DOM, you will have to set the innerText or innerHTML of your #old element.
You can accomplish this by changing your nFormatter() function like so:
var num = document.getElementById("old");
function nFormatter(num) {
var oldNumber = num.innerText;
var newNumber = oldNumber;
if (oldNumber >= 1000000000) {
newNumber = (oldNumber / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
}
if (oldNumber >= 1000000) {
newNumber = (oldNumber / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
if (oldNumber >= 1000) {
newNumber = (oldNumber / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
num.innerText = newNumber;
}
OR you can pass it just the number and use the returned result to set the innerText or innerHTML
var num = document.getElementById("old");
function nFormatter(num) {
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return num;
}
num.innerText = nFormatter(num.innerText);
Here is an updated codepen. You were doing <= the upper bound and >= the lower bound on each if statement. This would cause multiple if's to be true. Also, have to make sure you call your function after you create it and I would advise not using the same name for a global variable and a parameter to a function. It can cause some confusing behavior.
var value1 = document.getElementById("old");
function prettifyNumber(value) {
var thousand = 1000;
var million = 1000000;
var billion = 1000000000;
var trillion = 1000000000000;
value = parseInt(value);
var retVal = "";
if (value < thousand) {
retVal = String(value);
}
if (value >= thousand && value < million) {
retVal = Math.round(value/thousand) + 'k';
}
if (value >= million && value < billion) {
retVal = Math.round(value/million) + 'M';
}
if (value >= billion && value < trillion) {
retVal = Math.round(value/billion) + 'B';
}
if(value > trillion) {
retVal = Math.round(value/trillion) + 'T';
}
value1.innerHTML = retVal;
};
prettifyNumber(value1.innerText);
In both attempts you are missing a basic step, that is: you are not invoking the function.
The fact that you are calling the function argument with the same name of the variable is not enough. On the contrary, the function argument hides the external variable, that therefore won't be accessible by name inside the function. Anyway, this is just an additional consideration, not the real problem.
Consider attempt 1. After the function definition, you should add the actual invocation, something like
document.getElementById("old").innerText = nFormatter(num);
Attempt 2 has basically the same issue (i.e. no function call), but also you must obtain the desired element (with document.querySelectorAll for instance) before handing in to the prettifyNumber function.
Summarizing, the first attempt is the most correct one among the two, keeping in mind that both functions work fine.
Ok, I'm still a beginner at JavaScript, but I'm trying to write a rock-paper-scissors type game. Everything is working pretty well, except that every time that I run the "reload" function the output is whatever is the first "if" statement of the second if/else statement. By this I mean that the output "Both sides reload." would come back every time if the code were to be arranged how it is below. Also I already know that the randomizer works. Any help will be greatly appreciated. Thanks.
var reload = function() {
var random = function() {
var randomizer = Math.random() * 100
if (randomizer <= 33) {
var compDecision = 1
}
else if (randomizer > 67) {
var compDecision = 2
}
else if (33 < randomizer && randomizer <= 67) {
var compDecision = 3
}}
if (compDecision = 1) {
confirm("Both sides reload.")
}
else if (compDecision = 2) {
confirm("You reload and the enemy takes up defensive positions.")
}
else if (compDecision = 3) {
confirm("The enemy takes you out as you reload.")
}}
First of all use = for assignments, and == for logical compare operation.
Then you should declare var compDecision as a empty or default var and then assign to it a value without using var again. I would recommended using semi-colons ; to end your statements, unlike JavaScript, they are not optional for other languages.
Here is your working code, check the differences conclude the solution:
var reload = function () {
var compDecision = 0;
var random2 = function () {
var randomizer = Math.random() * 100
if (randomizer <= 33) {
compDecision = 1;
} else if (randomizer > 67) {
compDecision = 2;
} else {
compDecision = 3;
}
}
random2();
if (compDecision == 1) {
alert("Both sides reload.");
} else if (compDecision == 2) {
alert("You reload and the enemy takes up defensive positions.");
} else if (compDecision == 3) {
alert("The enemy takes you out as you reload.");
}
}
reload();
Tested here : http://jsfiddle.net/urahara/6rtt0w62/
The code is simple:
var i = 0.5;
if (i < 0) {
console.log('small');
} else {
console.log('big');
}
but the result is big!, what's wrong about my code?
The else part of your if-statement evaluates i >= 0. And 0.5 >= 0.
Perhaps you wanted to write:
if (i >= 0 and i < 1) {
console.log('small');
}
But I don't know what you would consider small ;-)
there is nothing wrong in your code, lets take a deep look on your 'if' condition, you will get the answer that 0.5 > 0
you may be want to write this
var i = 0.5;
if (i > 0) {
console.log('big');
} else {
console.log('small');
}
Your code logic is completely right...
0.5 is greater than 0