tic
tic

Reputation: 4189

how to get a reference for the caller element when the function has already a parameter

function myFunction(par) {
...
}


el1.onclick=myFunction(5);
el2.onclick=myFunction(7);

How to get a reference for the caller element inside myFunction?

Upvotes: 0

Views: 584

Answers (2)

thomasrutter
thomasrutter

Reputation: 117343

In your example, you are assigning the return value from myFunction(5) to el1.onclick, and the return value from myFunction(7) to el2.onclick.

Take the following example:

el1.onclick=myFunction(5);

In the above example, myFunction(5) is executed. Then the return value of that function, let's call it myval, is assigned to el1.onclick. This is equivalent to:

var myval = myFunction(5);
el1.onclick = myval;

It's not clear that this is what you intended. For this to work, the return value from myFunction would need to be a function (or a string of Javascript) to be executed later.

It is inside that function that you would refer to the caller element. this inside that function will return the element on which the event is currently being called.

Upvotes: 3

epascarello
epascarello

Reputation: 207511

//this is saying call this function and asign what it returns to onclick el1.onclick= myFunction(5);

You want to use a closure el1.onclick = function(){myFunction(5);}

To reference the element you can pass the object in

function test(elem, x){    
    elem.innerHTML = x;
} 

document.getElementById("foo").onclick = function(){ test(this, 1); }

example 1

or you can use call so that within the listener, this references the element.

function test(x){    
    this.innerHTML = x;
}

document.getElementById("foo").onclick = function(){ test.call(this, 1); }

example 2

Upvotes: 1

Related Questions