Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
Losing the value of a variable javascript

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();
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!