BusinessRx Community

Dedicated to the advancement of software, technology and the people who devote their lives to it.

Welcome to BusinessRx Community Sign in | Join | Help
in Search

BusinessRx Reading List

These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.

JavaScript Targets and the this Reference

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.

Published Monday, December 25, 2006 11:47 PM by OdeToCode Blogs

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server, by Telligent Systems
'