mike
mike

Reputation: 49198

How, using JavaScript, do I change an <a> tag's onclick event handler to a function with parameters?

I'm aware that you can set an onclick handler like this:

my_a = document.createElement('a');
my_a.onclick = somefunction;

... but what if somefunction takes a parameter? For the sake of simplicity, let's say I need to pass it the string "x". Is it possible to dynamically set the onclick handler to somefunction('x')?

Upvotes: 1

Views: 1408

Answers (4)

Matt Ephraim
Matt Ephraim

Reputation: 1360

The easiest way is to wrap it in an anonymous function. Like this:

my_a.onclick = function() { somefunction('x'); };

The downside is that this will no longer refer to my_a inside of the someFunction function, but if you don't need it to, then the anonymous function should work.

Upvotes: 0

Bouke
Bouke

Reputation: 12138

Then you would create an anonymous function:

my_a = document.createElement('a');
my_a.onclick = function() { somefunction(x); };

If you also like to refer to this in somefunction, you could use a library like [Prototype][1], then you would do something like:

my_a = document.createElement('a');
my_a.onclick = somefunction.bind(this, x);

[1]: http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding Blog article

Upvotes: 2

strager
strager

Reputation: 90012

You want to use what is called an anonymous function:

my_a.onclick = function() {
    somefunction(arguments, here);
};

If you want to retain "this" you can utilize closures:

my_a.onclick = function() {
    somefunction.call(my_a, arguments, here);
};

Upvotes: 2

Andreas Grech
Andreas Grech

Reputation: 107950

What you want is a partial function application:

function partial(func /*, 0..n args */) {
  var args = Array.prototype.slice.call(arguments).splice(1);
  return function() {
    var allArguments = args.concat(Array.prototype.slice.call(arguments));
    return func.apply(this, allArguments);
  };
}

Now, you will be able to do this:

my_a.onclick = partial(somefunction,1,2,3); //1,2,3 being some parameters

Upvotes: 1

Related Questions