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

Asked

Viewed 1,440 times

1

I’m not able to make a code work, where I create a function separately and call it whenever I 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 only works if I write the function name, without the parameters, like:

variavel.onclick = minhaFuncao;

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

NOTE: Without declaring the function right after onclick, I want it to be declared earlier, just change the parameters.

3 answers

1

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

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

Example:

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

variavel.onclick = function() {
    minhaFuncao(10, 20);
}
  • That goes for elemento.addEventListener also.

1

I do not know if I understood how you want to use the function, but this is the expected behavior. Think of 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);

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.