0

I am trying to use an object I am creating from a button click event. The object is available later in the code. The last console statement prints undefined. How can I return the object for use later in the code? Thank you.

const btn = document.getElementById('btn');
// Use IIFE to get human data from form
var getUserData = (
    function () {     
        function getInput() { 
          let formContainer = document.getElementsByClassName('form-container')[0];
          // Remove form from screen
          formContainer.classList.add('hide');
          //formContainer.style.display = 'none';
          let main = document.getElementById('grid');
          main.classList.remove('hide');
          main.classList.add('show');
          //main.style.display = 'flex';
          let name = document.getElementById('name').value;
                let feet = document.getElementById('feet').value;
          let inches = document.getElementById('inches').value;
          let height = (feet * 12) + inches;
          let weight = document.getElementById('weight').value;
          let diet = document.getElementById('diet').value;
            return { name: name, height: height, weight: weight, diet: diet};
        }
        return(getInput); 
})();

let human;

document.getElementById("btn").addEventListener("click", function (event) {  
    event.preventDefault();
    var user = getUserData();
    human = new Human(user.name, user.height, user.weight, user.diet);
    getHumanInfo(); // console logs the human
    return human; // returns udefined when I try to console log later in code
});

function getHumanInfo(){
  console.log(human);
}

// this returns udefined
console.log('Human: ' + human);
1
  • the human object will be undefined as the event listener code executes only when the event occurs so for the last console.log there exists no variable named "human" Commented Sep 9, 2020 at 4:54

1 Answer 1

1

You are adding an event listener, so the callback won't be called before a click is performed on the element with the id btn. And you are logging the variable human immediatly: it won't be defined because it hasn't been set yet.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Antoine. I moved the rest of my code to be executed inside the callback so I can then use the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.