How to pass parameters

I want to pass two parameters on button “b” click. how to pass parameters on b.onclick = test function?

   function test(x, y){
	alert(y);
}

var b = document.getElementById('b');

b.onclick = test; //how to pass x and y parameter?

Thanks!

Is that the only way? Can’t we call “test” directly with params?

Getting back to the original question, you can pass the parameters to a function, that returns a separate function. That returned function will retain access to the originally passed variables.


function test(x, y) {
    return function () {
        alert(y);
    }
}

var b = document.getElementById('b');
b.onclick = test(x, y);

b.onclick = function() { test(x,y); }

:slight_smile:

No, because if you call it directly it is executed directly.

try this:


function test(x, y){
alert(y);
}

var b = document.getElementById('b');

b.onclick = test(0,"Hello");

You will directly see a popup with “Hello”, because you are calling the function. using b.onclick=function() {text(x,y);} doesn’t have this problem, since you are defining the function, not calling it.