0

I am aware of the following three ways to set up an onclick event in javascript:

<element onclick="myScript">
object.onclick=function(){myScript};
object.addEventListener("click", myScript);

But when I try to do the following it doesn't work:

 object.addEventListener("click", myScript("value"));

How can I achive the desired result most elegantly?

COMisHARD
  • 867
  • 3
  • 13
  • 36

1 Answers1

1

javascript at Question calls myScript immediately. You can use Function.prototype.bind() to reference myScript and pass parameter "value" to myScript when invoked at click of object

function myScript(val) {
  console.log(val)
}

var object = document.querySelector("button");
object.addEventListener("click", myScript.bind(object, "value"));
<button>click</button>
guest271314
  • 1
  • 15
  • 104
  • 177