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!
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.
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.
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.
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 .
You can try event.currentTarget
instead of event.target
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With