Home > other >  Losing the value of a variable javascript
Losing the value of a variable javascript

Time:09-26

Why am I losing the value of a variable one? I tried to declare the variable as a global variable and it didn't work. I also tried some console.log commands, but didn't understand what happened.

function check() {
  document.addEventListener("DOMContentLoaded", ready);
}
let one; // 1
function ready() {
  let button = document.getElementById("transform");
  let div = document.getElementById("objectImg");
  let img = document.getElementById("dog");

  console.log(div);
  console.log(button);
  button.addEventListener("click", function(a) {
    if (img) {
      img.parentNode.removeChild(img);
      div.innerHTML = "<img id = 'red' src = 'img/cat.jpg'>";
      one = document.getElementById("red");
      img = false;
      console.log(one); // <img id="red" src="img/cat.jpg">
    } else {

      alert("some text");
    }
  });
  console.log(one); // undefined
  //  one.addEventListener("mouseover", (a) => {
  //     });
}
check();

CodePudding user response:

The reason is that you are setting the value to one inside an event listener. The code inside the event listener is executed after the button is clicked. So, set the value to one outside of the event listener

CodePudding user response:

In your code you are calling the one before it's initiated, so as per the below code you can call the function once the one variable is assigned with some values, then you will get value.

let one;

(function () {
  
  document.getElementById("button").addEventListener("click", function(a) {
  
    one = 56
  
    console.log('one from button click event: '   one)
    
    callWhenOneIsSet()
    
  })
  
})()

function callWhenOneIsSet() {
  console.log('one from callWhenOneIsSet: '   one)
}
<button id="button">Click it</button>

  • Related