Identifying the Target of an Event

Contact Us or call 1-877-932-8228
Identifying the Target of an Event

Identifying the Target of an Event

Often you will want to take action on the target of an event. For example, in a drag-and-drop application, you click down on an element and drag it around the screen. To write that code, you need to be able to identify which element receives the click.

In most modern browsers, this is done with the target property of the event itself. The following demo illustrates:

Code Sample:

<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="../Styles/propagation.css">
<script type="text/javascript" src="../../lib.js"></script>
<script type="text/javascript">
	observeEvent(window,"load",function() {
		var outer=document.getElementById("outer");
		var inner=document.getElementById("inner");
		var heading=document.getElementById("heading");
		observeEvent(outer,"click",function(e) {
		}, false);
		observeEvent(inner,"click",function(e) {
		}, false);
		observeEvent(heading,"click",function(e) {
		}, false);
	function findTarget(e) { += " | click | ";
	<h1 id="heading">Target</h1>
	<div id="outer">outer
		<div id="inner">inner</div>

In your browser, click on any of the elements: outer, inner, or the h1 element and the word "click" will get added to the element.

Unfortunately, if you try this in IE8 and earlier, you will get an error something like "'target' is null or not an object". IE8 and earlier use a different property to identify the target element: srcElement.

In ClassFiles/lib.js, there is a cross-browser getTarget() function shown below.

function getTarget(e) {
	e = e || window.event;
	var target = || e.srcElement;
	return target;