Events jQuery runs automatically

Posted on

Question :

I have the following code:

      function teste(teste){
      $('element').on('click', teste('teste'));

When I run this code, the teste function is triggered without clicking the button, ie automatically.

And in the following code, everything works ok.

      function teste(){
      $('element').on('click', teste);

Why does not the first code work?


Answer :

When declaring a function, a reference to it is created with its name.

See the following example, slightly modified to “unbind” the names:

function teste(param){

Note that teste is a reference to the declared function. However, the moment you use the parentheses to the right of the reference, you are directly requesting the function to execute:

teste('teste') //executa a função 

If your intention is to pass a reference and parameters at the same time, this is not possible. At least not that way.

A possibility to pass arbitrary parameters to a function used in% of jQuery% can be found in the on() parameter, as per documentation .

See the following example:

    function teste(param) {
    $('elemento').on('click', {teste: 'teste'}, teste);

By passing an object with the data q property in the second argument of the teste function of jQuery, we can access its value when the on function is executed through the teste attribute of the received parameter.

Demo on Jsfiddle


Leave a Reply

Your email address will not be published. Required fields are marked *