OdeToCode IC Logo

JavaScript Targets and the this Reference

Tuesday, December 26, 2006

I've been catching up on JavaScript basics recently.

Here is a simple example to demonstrate the difference between the event target (where an event takes place), and the this reference (where an event handler is defined).

Consider the following hunk of HTML:

<div id="List">
    <ul>
        <li> One </li>
        <li> Two </li>
        <li> Three </li>
    </ul>
</
div>

We could write an event handler like so:

<script type="text/javascript">
  
  window.onload =
function()
  {
      List.onclick =  List_onclick;
  }
  
  
function List_onclick(e)
  {
      
var evt = e || window.event;
      
var evtTarget = evt.target || evt.srcElement;
      
      alert(evtTarget.nodeName);
      alert(
this.nodeName);
  }          

</script>

Clicking on one of the list items will reveal that evtTarget references an LI element, while this references the DIV element. I like this style, but for various reasons we often wire event handlers like so:

<div id="List" onclick="return List_onclick()">
    <ul>
        <li>One </li>
        <li>Two </li>
        <li>Three </li>
    </ul>
</
div>

And the script, which doesn't change a great deal:

<script type="text/javascript" >
    
    
function List_onclick(e)
    {
        
var evt = e || window.event;
        
var evtTarget = evt.target || evt.srcElement;
        
        alert(evtTarget.nodeName);
        alert(
this.nodeName);
        
return false;
    }

</script>

Clicking in a list item will show us that the evtTarget is still an LI element, but this.nodeName will now show as undefined. The function List_onclick in the second example is part of the global object, which doesn't have a nodeName.

I always have to think about what this will reference in JavaScript, which is one reason the language makes me queasy.