Attach argument to an onclick function

i have some elements that contain an onclick event. i’m needing to add an argument to various elements via javascript.

for example, before…

<div onclick="myFunction();"></div>

after…

<div onclick="myFunction(this);"></div>

side note: i’ve inherited a project that was made with an outdated javascript toolkit and there’s not a way to attach the argument directly with their custom function. this cannot be changed.

You’d be better off taking that event out of the HTML and adding it using the .onclick attribute. That way you can “store” the arguments in a function closure which will be accessible during the click event.

This code will be similar to calling myFunction(“foo”, “bar”). Within myFunction, the value of this will be the div


<div id="mydiv"></div> 
<script> 
mydiv= document.getElementById("mydiv"); 

mydiv.onclick= function() {
     var myarguments= ["foo", "bar"]; 
      myFunction.apply(this, myarguments); 
})(); 
</script> 

Hope that helps. If you could provide more details about the arguments (where are they coming from? How are they populated? etc.) it would probably help.

I’m not sure I understand your question. Do you want to know how to use the parameters within the function itself, or are you trying to add more parameters to one function call?

And why are you using the onclick attribute instead of adding event listeners?

I’m the second who do not understand the question, but technically speaking function is an object, which has an “arguments” attribute . So you can make something like this:

function foo() {
alert(foo.arguments[0] + " " + foo.arguments[1]);
}

foo.arguments[0] = ‘aaa’;
foo.arguments[1] = ‘bbb’;

foo();