javascript event: e.currentTarget vs. e.target

JS events usually have two properties: e.currentTarget & e.target

As you may know, when you click on an element, ‘click’ event bubbles up to <body> node of your element.

Let’s have a look at this code:

<body><p><a href="#">some <span>text</span></a></p></body>

If someone click on ‘text’, a click event will be created and bubble up from <span> node up to <body> node (going throug <span>, <a>, <p> and <body> respectively – provided we did not stop event bubbling with our js code).

You can attach an event on any of these nodes (<body>, <p>, <a>, <span>) and your event-listener will fire up as click event bubbles up to the top node. Here is the difference between event.currentTarget and event.target.

  • event.target is the node from which the event originated, ie. wherever you place your event listener (on <p> or <span>), event.target refers to <span> node (where user clicked).
  • event.currentTarget, on the opposite, refers to the node on which current-event listener was attached. Ie. if we attached our event listener on <p> node, then event.currentTarget refers to <p> while event.target still refers to <span>.
    Note: that if we also have an event listener on <body>, then for this event-listener, event.currentTarget refers to <body> (ie. event provided as input to event-listerners is updated each time event is bubbling one node up).

Note: we only dealt with bubbling-up events as they are most commons, but normally prior to bubbling-up, event bubbles down from <body> to clicked-item (but since this is not implemented in prior versions of IE, it’s almost useless)

4 Comments: Trackback URL | Comments RSS

  1. Darren Says:

    Thanks for the info, helped me clarify an error that I was experiencing in my code.
  2. leanne Says:

    Yeah, nearly two years after you posted this, it is still helpful! This post explained simply something I needed to know just now, with the perfect title for me to find it! Thanks very much!
  3. xqwzts Says:

    older versions of IE have srcElement instead of currentTarget so you can use this little snippet to get whichever you need: var thehrefelement = (e.currentTarget) ? e.currentTarget : e.srcElement;
  4. Stephen Morley Says:

    @xqwzts: IE's e.srcElement property is the equivalent of e.target and *not* e.currentTarget.

Post a Comment

Your email is never published nor shared. You're allow to say what you want...