SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Feb 2003
    Location
    eez
    Posts
    331
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Event target and relatedTarget not always the correct one?

    Hi!

    I heard somewhere that the event.target isn't the real target sometimes. Is this true?

    And what about relatedTarget?

    Thanks

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi aqw,

    event.target is always the target of the event, however, sometimes it might not be what you expect. For example...
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <style type='text/css'>
    div {
      width: 50%;
      margin: 2em;
      border: 1px solid #000;
    }
    </style>
    <script type='text/javascript'>
    window.onload = function()
    {
      var p = document.getElementById('parent');
      p.addEventListener('click', parentOnClick, false);
    }
    function parentOnClick(e)
    {
      var s = 'target: ' + (e.target ? e.target.id : 'null');
      s += '\ncurrentTarget: ' + (e.currentTarget ? e.currentTarget.id : 'null');
      alert(s);
    }
    </script>
    </head>
    <body>
    
    <p>Click on one of the following elements:</p>
    
    <div id='parent'>
      parent
      <div id='child'>
        child
        <div id='grandchild'>
          grandchild
        </div>
      </div>
    </div>
    
    </body>
    </html>
    First let me say that the example code is only for DOM2Events-compliant browsers (not IE6). Also, this demo is only concerned with the bubbling phase of event propagation.

    Note that the event listener is registered on the parent element. Click events on the child and grandchild elements will bubble up to the parent. If you play with the demo you will quickly see the difference between target and currentTarget. target points to the element clicked on. currentTarget points to the element whos onclick handler is currently handling the event. In the listener, currentTarget is almost always equal to this.

    relatedTarget is a mouse event property. A very quick summary: For mouseover, it points to the element the mouse was previously over. For mouseout it points to the element the mouse is now over.

  3. #3
    SitePoint Addict
    Join Date
    Feb 2003
    Location
    eez
    Posts
    331
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks!!!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •