6

I'm trying to use event.target to find the exact element that's been clicked. I'm working with jQuery Mobile, and the links are in navbars.

When the page initially loads, event.target does it's job and returns the correct 'a' element (there's a programmatic click in there causing that) . However, when you click on a link, event.target returns a 'span' element and not the 'a' element that's been clicked.

If you click the surrounding area of the text part of the link, the correct 'span' element is returned by event.target.

I need event.target to return the exact 'a' element that's been clicked, no matter if you click directly on the link or not, as long as the user clicks in the given area of the link (including the 'span' areas).

You can see it in action here

Let me know if I need to provide any more information. Thanks!

Justin White
  • 714
  • 7
  • 22
  • I guess this might help: http://stackoverflow.com/questions/1522941/event-propagation-in-javascript, also see: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow – m90 Mar 12 '12 at 09:51

2 Answers2

17

You can try event.currentTarget instead of event.target

Valentin Kantor
  • 1,799
  • 1
  • 23
  • 27
  • 1
    Best answer. From what I've looked up, event.currentTarget seems to be the element that the listener is attached to, where event.target is just the front-most tag that wraps the text the user clicked on. – Robert Apr 03 '21 at 18:40
10

Use this:

   var target=(event.target.tagName=='A')
                ? event.target
                : $(event.target).closest('a')[0]

it will return the ascendent A-element when you click on a child of the link

or simply: this

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201