1

I have a method which is called by a button and which I can't modify for some reason.

<button onclick="onMyButtonClick()">button1</button>
<button>button2</button>

function onMyButtonClick() {
  // how to know who is a caller?
}

how to know who is a caller?

UPDATE:

<button onclick="onMyButtonClick(123)">button1</button>
<button>button2</button>

function onMyButtonClick(a, b) { // b is undefined
  // how to know who is a caller?
}
Mario
  • 185
  • 9

3 Answers3

1

You could use javascript event.

event.srcElement

Gives to you the dom element that calls the the function.

See this example:

function onMyButtonClick() {
  alert(event.srcElement.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="onMyButtonClick()">button1</button>
<button onclick="onMyButtonClick()">button2</button>
Juan Caicedo
  • 1,425
  • 18
  • 31
  • This is the best answer if the parameters can't be changed. `srcElement` is more descriptive than `target` – 4castle Mar 05 '16 at 17:34
0

See this example:

arguments.callee.caller and event.target

https://jsfiddle.net/cb3fcbL6/1

user2190492
  • 1,174
  • 2
  • 9
  • 37
0

Pass this as the parameter to the function.

HTML

<button onclick="onMyButtonClick(this)">button1</button>

JavaScript

function onMyButtonClick(button) {
    //button is the DOM element that called the function
}
4castle
  • 32,613
  • 11
  • 69
  • 106
  • This is the best solution because anybody who goes back to read the code would have no difficulty understanding what you're trying to accomplish. It's self-explanatory. – 4castle Mar 05 '16 at 16:19
  • except that you've forgotten something. – Mario Mar 05 '16 at 17:10
  • If you can't edit the html file though in order to change the parameter, then use Juan's solution `var button = event.srcElement` to get the DOM element. It's just that using `event` would be confusing because it's being used for an unusual purpose. – 4castle Mar 05 '16 at 17:15
  • @Mario what did I forget? – 4castle Mar 05 '16 at 17:31