Sumtinlazy Sumtinlazy - 6 months ago 12
Javascript Question

Having trouble subtracting variables while using jQuery

I'm pretty new to jQuery and javascript as a whole. I was having trouble while subtracting different variables while using

.click
jQuery. I'm trying to have the value of nmeHealth to be lowered by the variable adjustdmg.

Variables

var defdamage = 20;
var strength = 1;
var adjustdmg = strength + defdamage - 1;
var nmeHealth = 100;


Function

$("#enemy").click(function() {
if (nmeHealth >= 0) {
$("#enemyHealth").html(nmeHealth);
var nmeHealth = nmeHealth - adjustdmg;
}
})

Answer

var nmeHealth is the problem because it means you're instantiating a new variable (and it belongs to the function scope) instead of modifying the old one. The line:

var nmeHealth = nmeHealth - adjustdmg;

should be:

nmeHealth = nmeHealth - adjustdmg;

or shortly:

nmeHealth -= adjustdmg;

Also, if you want to show the current enemy health, and not lag one cycle behind, change the order of the lines as well. I'm talking about this code here:

$("#enemyHealth").html(nmeHealth);
var nmeHealth = nmeHealth - adjustdmg;

Final version:

nmeHealth -= adjustdmg;
$("#enemyHealth").html(nmeHealth);