skip to Main Content

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


  1. 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.

    1. The update function is never called, there needs to be a listener on the keyboard events

    2. 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

    document.addEventListener("keydown", function(event) {
    
      // Check if pressed key is Up Arrow (keyCode 38) or Down Arrow (keyCode 40)
      if (event.keyCode === 38 || event.keyCode === 40) {
        let currentValue = parseInt(document.getElementById("numberInput").textContent);
        
        const increment = event.keyCode === 38 ? 1 : -1; // Add 1 for Up Arrow, subtract 1 for Down Arrow
        const newValue = currentValue + increment;
        document.getElementById("numberInput").textContent = newValue;
    
      }
    });
    <div id="numberInput">100</div>
    Login or Signup to reply.
  2. The health variable is in no way connected to the textNode you created. Therefore if you change the value in health 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.

    let health = 100;
    const textNode4 = document.createTextNode(health);
    const updateHealthUi = (el, health) => el.textContent = health;
    
    document.body.appendChild(textNode4);
    
    document.addEventListener('keydown', e => {
      e.preventDefault();
      switch (e.key) {
        case "ArrowUp":
          health = Math.min(100, ++health);
          break;
        case "ArrowDown":
          health = Math.max(0, --health);
          break;
      }
    
      updateHealthUi(textNode4, health); // update the UI to show the new value
    })
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search