Search code examples
javascriptfunctionreturn

How to call a function that is using window.onload from another function


I'm trying to use questionFunction() again once the user clicks a button which calls myFunction but I'm getting an error 'questionFunction is not defined'

window.onload = function questionFunction() {
  var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}

function myFunction() {
return questionFunction();
}

I wan't the text to be changed on load and also again once the user clicks to call myFunction()


Solution

  • function questionFunction() {
      var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
    }
    
    window.onload = questionFunction;
    
    function myFunction() {
      return questionFunction();
    }
    

    This will work. You're getting error because of wrong function scope.

    You can read about it here:

    https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/