Search code examples
javascriptreferencecalladdeventlistener

addEventListener - Specifying a function reference with attributes


The problem: In the line adding the event listener to element with ID "g1", fnk is called when this line is executed i.e when the event listener is added. I want the fnk function to be called only when the blur event occurs with g1

   function fnk(t)
    {
      //I play with t here
    }

    var x = document.getElementById("g1") ;
    x.addEventListener("blur", fnk(x),false) ;
    x.focus() ;

I understand that addEventListener takes a function reference and not a function call.

Note: My understanding of a function reference ("fnk") is that it is the function name without the following "()" and only refers to the function and a function call i.e. the function name followed by "()" , that is fnk(), calls the function.

Hence the right way would be

x.addEventListener("blur", fnk, false) ;

Solves the problem of fnk being called while adding the event listener. The problem with the above line is that fnk is called on blur without passing the argument "t" that results in a " t is not defined" error.


Solution

  • You can get around that by surrounding it with an anonymous function:

    x.addEventListener("blur", function(){ fnk(x) },false) ;