SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist NokX's Avatar
    Join Date
    Feb 2003
    Location
    Knoxville, TN
    Posts
    525
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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...

    Code:
    <div onclick="myFunction();"></div>
    after...

    Code:
    <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.

  2. #2
    SitePoint Evangelist TommiChi's Avatar
    Join Date
    Oct 2008
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

  3. #3
    SitePoint Member
    Join Date
    Jul 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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();

  4. #4
    SitePoint Member
    Join Date
    Jul 2010
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

    Code:
    <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.


Bookmarks

Posting Permissions

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