undefined function in window.onload?

1

Well I declare a function in a javascript file

javascript file:

window.onload = function(){
   function func(x,y){
      //faz operacoes em x e y e nao retorna nada
   }
}

But in the html file, when I want to call this function by passing the parameters x and y

html file:

<script type="text/javascript">
     func(2,3);
</script>

It's the error in the html file saying that the function is undefined, I already tried to do something like

<script type="text/javascript">
    window.onload = function() {
       func(2,3);
    }
</script>

I'm not sure what to do, but I do not know what to do with it,

Note: I'm using global variables, besides the fact that my algorithm is too large to put into html, so if you can tell me a way to pass the parameters of a javascript function in html would help me a lot

    
asked by anonymous 23.03.2017 / 20:04

1 answer

2

This happens because the func function is defined only within the scope of window.onload . You need to declare it before calling it, as in this example:

//Coloquei um alert apenas para fins de teste
function func(x,y){
    alert(x + y)
}

//Aqui a função estará declarada quando chama-la
window.onload = function(){
    func(2,3);
}

//Assim, poderá chamá-la em outro lugar, por exemplo clique de botão
document.getElementById("botao").click = function () { func(2,3); }

If you declare it within onload , it will only be visible there, and if you call it anywhere else on the page, it will not exist, so it gave the undefined error

    
23.03.2017 / 20:18