View Full Version : Attachning event hanlders programmatically

02-08-2007, 08:14 AM
Hi there,

I would like some clarification on how to attach event handlers programmatically.

In my understanding, if I have a function with no arguments, as follows:

function methodOne() { alert("hi"); }

To attach this function to the click event of a button, I can do something like this:

document.getElementById("buttonId").onclick = methodOne;

which is equivalent to:

<input type="button" onclick="methodOne()"/>

but what if I have a function that accepts parameters, like:

function methodTwo(butt) { if(butt.value =="") .... }

Is it possible to attach this function to all buttons on my page dynamically (like when the page loads)? How do I deal with passing in parameters in this case? Do I have to write the function to use the arguments array?

Thanks for your help in this regard.

Bill Posters
02-08-2007, 08:45 AM
window.onload = doIt;

function doIt() {

if (!document.getElementsByTagName) return;

var inputEls = document.getElementsByTagName('input');
for (var i = 0, inputEl; inputEl = inputEls[i]; i++) {
if (inputEl.type == 'button') {
inputEl.onclick = function() { methodOne(arg1); }

The possible issue with this approach is that it over-writes any previous onclick event for the targeted objects. If you know that none exist, and that none are ever likely to, then the above outline will work without issue.

However, you should look around at the handful of custom addEvent functions which have been written. You could use one to apply both the onclick on the button inputs as well as to add the methodOne to the window.onload event.


Philip M
02-08-2007, 08:47 AM
Lots of tutorials on this to be found on the web, e.g.:-