Javascript - How to pass parameters to a function of an Event Attribute

1

I'm not able to run a code, where I create a function separately and call it whenever you want, but only changing the parameters. Javascript does not execute

function minhaFuncao(num1, num2) {
    //codigo
}

variavel.onclick = minhaFuncao(num1, num2);

How do I make it work? It just works if I write the function name without the parameters, type:

variavel.onclick = minhaFuncao;

But I would like to pass parameters to the function after the "onclick".

    
asked by anonymous 23.03.2018 / 07:25

3 answers

1

When you use minhaFuncao(num1, num2); , JavaScript interprets that you are calling the function and want it to run, so it does not work that way.

In your case, you need to create an anonymous function and within that function call another (passing parameters, of course).

Example:

function minhaFuncao(num1, num2) {
    alert( num1 + num2 )
}

variavel.onclick = function() {
    minhaFuncao(10, 20);
}
    
23.03.2018 / 07:50
1

I do not know if I understand how you want to use the function, but this is the expected behavior. Think of the onClick as an event that can be triggered at various times in the code, but you have to pass the parameters when calling the event. For example:

var Evento = {
  onClick: null
}

function soma(n1, n2){
  var sum = n1+n2;
  console.log("Soma: "+sum);
}

//Configura ação do evento - handler
Evento.onClick = soma;

//Usuário faz alguma ação e vc dispara o onClick
Evento.onClick(1,1);

//Usuário faz outra ação e vc dispara outro onClick
Evento.onClick(2,2);
    
23.03.2018 / 08:29
1

You can use the method bind()

var button = document.querySelector('button');
function minhaFuncao(num1, num2) {
  alert(num1 + num2);
}
button.onclick = minhaFuncao.bind(null, 2, 2);
<button>CLIQUE</button>

Reference

23.03.2018 / 09:59