Javascript element.onlick function with parameter

July 10, 2010 - 5:56am
Submitted by gary

A simple trick I found not many people know about:

 

to pass allow parameter to pass in when assigning functions:

<html>
<body>

<a id="test1" href="#">test</a>

<script type="text/javascript">
var test1 = document.getElementById("test1");

test1.onclick = new Function("sayHi('nice man!')");

 function sayHi(stuff){ alert("hi " + stuff);}
</script>

</body>
</html>

 

This works with onclick, onmouseover and all other event driven functions

 

no time to check if this will be compatible with jquery or prototype call back function parameters.

But i think it should work.

 

The key is the

new Function("functioName(parameters)")

 

live example: test

 
You may also find the following articles interesting: