Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.target not returning the exact element that has been clicked

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!

like image 442
Justin White Avatar asked Mar 12 '12 09:03

Justin White


People also ask

How do you know which element is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.

How do you get the element that triggered an event?

Answer: Use the event. target Property You can use the event. target property to get the ID of the element that fired an event in jQuery. This property always refers to the element that triggered the event.

Why is event target undefined?

You're likely getting this error because you're trying to get a name attribute on elements that don't have a name attribute. For example; input, textarea, and form elements are naturally able to get a name attribute. But elements like div, span doesn't.

Why is event currentTarget null?

currentTarget is only available while the event is being handled. If you console. log() the event object, storing it in a variable, and then look for the currentTarget key in the console, its value will be null .


2 Answers

You can try event.currentTarget instead of event.target

like image 123
Valentin Kantor Avatar answered Oct 20 '22 04:10

Valentin Kantor


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

like image 10
Dr.Molle Avatar answered Oct 20 '22 04:10

Dr.Molle