Anonberg
Anonberg

Reputation: 41

Set a parameter when changing a button onclick function?

Yesterday I made this post: Button Function Working Without Click, trying to figure out why my code wasn't working for a document.getElementById("examplebutton").onclick = function();, but the problem is I can't set parameters on the function() because the parentheses would make the button auto-fire.

Does anyone know how to put parameters in a line of code similar to this:

<button id="button" onclick="function1">BIG BUTTON THING</button>
 document.getElementById("button").onclick=function2

(I would want the parameter set to be for function 2)?

Upvotes: 0

Views: 838

Answers (1)

Botlin
Botlin

Reputation: 36

What you need is a closure. Just wrap you function call into another one.

var myButton = document.getElementById("examplebutton");
myButton.onclick = function(){
    myButtonFunction('some parameters');
};

function myButtonFunction(param){
    console.log(param);
}

Upvotes: 2

Related Questions