mister_b
mister_b

Reputation: 307

Passing parameters to a function in an onclick event

I'm trying to dynamically build some HTML and assign a function to the onclick event of a link. Here's the code I've got...

link = document.createElement("a");
link.setAttribute("href", "#");
link.onclick = function(){someFunction(myObject.id);};
link.appendChild(document.createTextNode("Click Me!"));

My research has indicated that I wrap my function call within an anonymous function like I have done. What I'm finding though is that my function is called when this bit of script runs instead of on the click event. This seems to be a common problem but I'm following all the advice I've found so far but to no avail.

Any help or pointers is much appreciated.

Mister B.

Upvotes: 1

Views: 3260

Answers (2)

onteria_
onteria_

Reputation: 70487

Maybe try this alternative method:

function someFunction(id) {
    return function() {
        alert(id);
    };
}

link = document.createElement("a");
link.setAttribute("href", "#");
link.onclick = someFunction(myObject.id);
link.appendChild(document.createTextNode("Click Me!"));

Upvotes: 1

jbrookover
jbrookover

Reputation: 5150

The code you've posted works fine - I just tested it. Here are some possibilities to look for..

  1. Where have you defined someFunction? Is it being called upon definition?
  2. Do you reference someFunction anywhere else? Perhaps that is what is triggering the issue.
  3. Any reason you're not using a javascript library like jQuery to do this? Simplifies a lot.

One debugging method would be to change that line to:

link.onclick = function(){alert('test'); someFunction(myObject.id);};

Is the alert popping up? My guess is not, suggesting #1 and #2 above. Feel free to post more code and we can look for the error elsewhere.

Upvotes: 0

Related Questions