javascriptdomaddeventlistener

How to pass arguments to addEventListener listener function?


The situation is somewhat like-

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.


Solution

  • There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

    function() { some_function(someVar); } 
    

    was created.

    Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

    var someVar; 
    someVar = some_other_function();
    alert(someVar);
    someObj.addEventListener("click", function(){
        some_function(someVar);
    }, false);