When a div is clicked i want to show some information. I have two divs with the same ids referring the same function. I want the event to be triggered only when the corresponding div is clicked. It is not happening as expected. I understand here because divs refer the same id the function is triggered to other div's also even though it is not clicked. I am confused on how to overcome this. Can someone guide me how to resolve this?
Aura Component:
<aura:component >
<aura:attribute name="collapseText" type="String" default="[+]"/>
<div>
<div class="Message">
<div style="width:90%;float:left">Individual Information</div>
<div class="expandCollapse" onclick="{!c.ToggleCollapse}">{!v.collapseText}</div>
</div>
<div class="container hide" aura:id="containerCollapsable">
<p>Hello</p>
</div>
</div>
<div>
<div class="Message">
<div style="width:90%;float:left">Group Information</div>
<div class="expandCollapse" onclick="{!c.ToggleCollapse}">{!v.collapseText}</div>
</div>
<div class="container hide" aura:id="containerCollapsable">
<p>Hello</p>
</div>
</div>
</aura:component>
Controller:
({
ToggleCollapse : function(component, event, helper) {
helper.ToggleCollapseHandler(component, event);
}
})
Helper
({
ToggleCollapseHandler : function(component, event) {
var existingText = component.get("v.collapseText");
var container = component.find("containerCollapsable") ;
if(existingText === "[ - ]"){
component.set("v.collapseText","[ + ]");
$A.util.addClass(container, 'hide');
}else{
component.set("v.collapseText","[ - ]");
$A.util.removeClass(container, 'hide');
}
}
})
Best Answer
The problem is that each section is using the same information. For example, when you toggle one collapse area, the other's +/- sign will also toggle.
The easiest way to resolve this is to create a new component:
From there, you can refactor your code:
Otherwise, if you don't want a separate component, you'll have to add more code to your component:
You can then determine which element to use based on the attribute value:
It'd also be easier if you could reorganize your code so that the collapse section contained the element to collapse, because then you could toggle the parent class directly. You could further ease your troubles by displaying the + or - via CSS, which would eliminate the need for the text attribute, which could further simplify your code.
Here's an example:
From there, you can then simply modify your CSS files as necessary: