1

I have multiple div element in my lightning component which are clickable and from all of them I'm calling the same controller method. I want to know the div name which is clicked in my component. I know I can have multiple controller methods but I just wanted to have only one. I tried event.getSource().getLocalId(); but its returning null.

Component:

<aura:component implements="flexipage:availableForAllPageTypes,forceCommunity:availableForAllPageTypes" access="global">
    <aura:attribute name="isFlowLaunched" type="boolean" default="false" />
    <aura:if isTrue="{!v.isFlowLaunched}">

        <aura:set attribute="else">
            <div class="slds-grid slds-gutters">
                <div aura:id="button1" onclick="{!c.clickHandler}" class="slds-col slds-size_2-of-12" >
                    <span ><img src="{!$Resource.lion}"/></span>
                </div>
                <div aura:id="button2" onclick="{!c.clickHandler}" class="slds-col slds-size_2-of-12">
                    <img src="{!$Resource.dear}"/>
                </div>
                <div aura:id="button3" onclick="{!c.clickHandler}" class="slds-col slds-size_2-of-12">
                    <span><img src="{!$Resource.tiger}"/></span>
                </div>
                <div aura:id="button4" onclick="{!c.clickHandler}" class="slds-col slds-size_2-of-12">
                    <span><img src="{!$Resource.tiger}"/></span>
                </div>
            </div>
        </aura:set>
    </aura:if>
</aura:component>

Controller:

({
    clickHandler : function(component, event, helper) {
        console.log("Clicked");
        var clickedBtn = event.target.getAttribute("aura:id");
        console.log(">>> Div Name... "+clickedBtn);
    }
})
2
  • did you have tried event.getSource().target ? Commented Feb 27, 2019 at 13:07
  • yes, its giving this error: Action failed: c:LightningImage$controller$clickHandler [event.getSource is not a function] Commented Feb 27, 2019 at 13:09

1 Answer 1

5

You can you dataset attribute to get the current clicked div.

<div data-id="thisDiv" aura:id="thisDiv">Click Me!</div>


clickHandler : function(component, event, helper) { 
    var id = event.currentTarget.dataset.id; //it will return thisDiv
    var getTargetedButton = component.find(id); //it will return the source button
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .