erik
erik

Reputation: 45

javascript to find the caller div. (or any other dom object)

I have the following html page:

<div id="a" onclick ="javascript:click();">a</div>
<div id="b" onclick ="javascript:click();">b</div>
<div id="c" onclick ="javascript:click();">c</div>

Now, The javascript function:

function click() {
   // how do I know if it was 'a' , 'b' or 'c' to call me 
}

Does anybody know how to find (in every browser) which div was the caller in the 'called' click function ?

Many Thanks Erik

Upvotes: 4

Views: 4009

Answers (3)

WSkid
WSkid

Reputation: 2786

Something along the lines of:

js:

function click(elem){
     alert(elem.id);
}

html:

<div id="a" onclick ="javascript:click(this);">a</div>
<div id="b" onclick ="javascript:click(this);">b</div>
<div id="c" onclick ="javascript:click(this);">c</div>

Upvotes: 3

Sarfraz
Sarfraz

Reputation: 382806

Pass this as function argument:

<div id="a" onclick ="javascript:click(this);">a</div>
<div id="b" onclick ="javascript:click(this);">b</div>
<div id="c" onclick ="javascript:click(this);">c</div>

And here is the function:

function click(el) {
  alert(el.id);
}

It would have been easier and unobtrusive with jQuery though:

$('div').click(function(){
  alert(this.id);
});

Upvotes: 0

Dagg Nabbit
Dagg Nabbit

Reputation: 76766

Hint:

<script>
function click(me) {
   alert(me.id);
}
</script>
...
<div id="c" onclick ="click(this);">c</div>

Upvotes: 0

Related Questions