Reputation: 183
I created an image element and added attributes to it. I also added a function to an onclick event by doing:
img.onclick = change;
Now I want to add another function which has a parameter to my onclick event. Lets say I want to add:
retrieveClass(this.className);
How can I do this? Something like...
img.onclick = change, retrieveClass(this.className);
Upvotes: 0
Views: 145
Reputation: 12024
You can use bind method which refers to the function, eg:
img.onclick = retrieveClass.bind(img, img.className);
^^^
this
is equivalent to:
img.onclick = function(){
retrieveClass(this.className);
}
Upvotes: 1
Reputation: 46361
When you want to have multiple event handlers triggered by a single event, the standard method is to use addEventListener
(doc).
Assuming in your sample, change
is the name of a handler function, and retrieveClass(this.className)
returns another handler function, you could do this:
img.addEventListener('click', change);
img.addEventListener('click', retrieveClass(this.className));
Upvotes: 3
Reputation: 2815
This is the simplest...
<img src="..." onclick="command1; command2;">
You should use a function for this:
function imgClicked() {
command1;
command2;
}
Of course, you can declare it also with
img.onclick = function () { command1; command2; }
Upvotes: 1
Reputation: 342
Create a wrapper function containing both function calls then bind that to your onclick.
function wrap() {
change;
retrieveClass(img.className);
}
img.onclick = wrap();
Upvotes: 0
Reputation: 2767
img.onclick = function () { change; retrieveClass(this.className); }
Upvotes: 1