Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check which html element triggers onclick

I have html like below:

<div onclick=" callJavascript()">

<span id="abc"> abc </span>
<span id="def"> def </span>
<span id="ghi"> ghi </span>

</div>

When I click 'abc' or 'ghi', is there anywhere inside function callJavascript(), to find out which span id I clicked on ?

like image 854
cometta Avatar asked Dec 04 '22 08:12

cometta


2 Answers

Yes there is :

For Not IE browsers :

function callJavascript ( e ) {

    alert(e.target); // the DOMElement object
    alert(e.target.id); // the object's id

}

For IE :

function callJavascript ( e ) {

    alert(e.srcElement); // the DOMElement object
    alert(e.srcElement.id); // the object's id

}

You must nevertheless adapt your html :

<div onclick=" callJavascript(e)"> // replace "e" by "event" in IE.

<span id="abc"> abc </span>
<span id="def"> def </span>
<span id="ghi"> ghi </span>

</div>

If you want a more complete reference, here it is : http://www.quirksmode.org/js/events_properties.html

Wow ! May I mention, for better accuracy, your event listener should not be on the div element, instead, it may be triggered by the span elements themselves. The target or srcElement being the one on which the event occurs.

It's not part of the question, but it's worth saying : I usually prefer to avoid event attachment in html code since it causes scope problems and forces you, as in your case, to manually pass the event parameter.

like image 142
dader Avatar answered Dec 19 '22 10:12

dader


You have to add the event param to your onclick listener to have the event accessible within your listener.

<div onclick="callJavascript(event)">

Then use the target or srcElement property to get the DOM element.

function callJavascript(e) {
    var target = e.srcElement || e.target;
    alert(target.id);
}

Working demo

like image 24
DanielB Avatar answered Dec 19 '22 08:12

DanielB