I am trying to get the attribute value of the element clicked in my javascript code but for some reason the value I am getting is undefined.
This is the code:
HTML:
<c:button buttonLabel="Skype" buttonClass="valmetSecondaryButton noMargin" id="I_WANT_THIS_VALUE" onclick="{!c.openSkype}"/>
JS:
console.log(event.currentTarget.id);
This is working on Internet Explorer, havent tested in Firefox, but not working in Chrome. Also just so you know I am using Lightening Component, Salesforce!
Although not directly related to salesforce-lightning as your question is tagged, this thread is the first result when searching for evt currentTarget undefined so i'll leave my general answer here:
I've encountered a weird issue where event.currentTarget was undefined when it definitely shouldn't be - and it even appeared to be defined at the start of the event handler, but just disappear later.
It turns out that evt.currentTarget may disappear from the event when execution is passed on from the event - for example when awaiting a network request or trying to access the event from a setTimeout.
From MDN docs:
Note: The value of event.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.
This can also be demonstrated with the following code at the top of the event handler:
console.log(e.currentTarget);
setTimeout(()=> console.log(e.currentTarget), 0);
If you want to run some async actions before using event.currentTarget, you can probably just save the value of event.currentTarget into a variable before the async actions, and then later use the variable.
let elem = event.currentTarget;
await doSomethingAsync();
console.log(elem);
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