Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Aug 2002
    Location
    Cape Town, South Africa
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Attachning event hanlders programmatically

    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:

    Code:
    function methodOne() { alert("hi"); }
    To attach this function to the click event of a button, I can do something like this:

    Code:
    document.getElementById("buttonId").onclick = methodOne;
    which is equivalent to:

    Code:
    <input type="button" onclick="methodOne()"/>
    but what if I have a function that accepts parameters, like:
    Code:
    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.

  • #2
    Senior Coder
    Join Date
    Feb 2003
    Posts
    1,665
    Thanks
    0
    Thanked 27 Times in 25 Posts
    Code:
    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.

    http://www.quirksmode.org/blog/archi..._winner_1.html
    http://www.dustindiaz.com/rock-solid-addevent/
    Last edited by Bill Posters; 02-08-2007 at 07:48 AM.

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •