razoes
razoes

Reputation: 183

Add two or more functions to an onclick event

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

Answers (5)

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

Amit
Amit

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

Richard
Richard

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

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

Jacob
Jacob

Reputation: 2767

img.onclick = function () { change; retrieveClass(this.className); }

Upvotes: 1

Related Questions