This is a short example but when the variable "health" changes it wont change in the text?
health = 100;
var health = health
let textNode4 = document.createTextNode(health);
document.body.appendChild(textNode4);
function update() {
if (keyboard.e)
health -= 1;
if (keyboard.q)
health += 1;
}
I want it to change the variable "health" so you can see it on the text.
2
Answers
I see several reasons why this is not working, please provide a minimum runing version to replicate the error.
But on first eyesight there are two main issues.
The update function is never called, there needs to be a listener on the keyboard events
The health variable is appended before any code on it has been ran. I would add some code inside the update function to update it ie.
document.getElementByd('field_id').innerHtml = health
.With this in mind below is a snippet of how it could be implemented
The
health
variable is in no way connected to the textNode you created. Therefore if you change the value inhealth
you will need to manually update the DOM to display its new value.Below is a working example of how to do this. Note that I used a
keydown
event handler on the up and down arrow keys to change the value, but this can easily be changed for whatever business logic you require.