myEvent.target in DOM Level 2 Events
The object which caught the event.
This property is read-only.
- Property Type
- EventTarget
The following (HTML-centric) example shows the difference between Event.currentTarget
and Event.target
:
<p id="para" style="padding:1em; background-color:yellow">
Hello <b id="bold">World</b>
</p>
...
<script type="text/javascript">
function SayWhoCaughtMe(evt){
alert("target is :"+evt.target.id);
alert("currentTarget is :"+evt.currentTarget.id);
}
document.getElementById('para').addEventListener('click',SayWhoCaughtMe,false);
</script>
In the above, if the user clicks in the yellow area around the word "World", the first alert will show 'bold'; evt.target
refers to the top-most object which caught the event. The second alert will say 'para', as currentTarget
always refers to the object to which the event handler was assigned.
Note that if the user clicks on the word "World" itself, or the word "Hello", the first alert may show 'undefined', as evt.target
may refer to the Text
node containing the text. (Safari behaves this way, while Mozilla does not support event trapping on Text
nodes, instead always setting target
to the parent node of any text.)
Internet Explorer's event object does not support this property, but its srcElement
property is almost directly analogous. The only difference is that the srcElement
property will never refer to a Text
node (called a TextNode
by MS), but always to the parent node of any text which caught the event.