You have to toggle the slds-is-open
class from the top most div of the dropdown.
Let's say this is your dropdown:
<div class="slds">
<div aura:id="ddId" class="slds-dropdown-trigger slds-dropdown-trigger--click slds-is-open" onclick="{!c.toggleVisibility}">
.....
</div>
</div>
Now in the controller:
toggleVisibility : function(component, event, helper)
{
var ddDiv = component.find('ddId');
$A.util.toggleClass(ddDiv,'slds-is-open');
}
This should do. You can call this toggleVisibility function from blur of the button as well to close the dropdown.
Have this on the button :
onblur="{!c.toggleVisibility}"
UPDATE:
After VarunC's comment that the dropdown hides as soon as you click on it. To avoid that, update the toggleVisibility function which will hide the menu options after small delay.
toggleVisibility : function(component, event, helper)
{
setTimeout(function(){
var ddDiv = component.find('ddId');
$A.util.toggleClass(ddDiv,'slds-is-open');
}, 300);
}
Just use the onblur
event and $A.util.toggleClass
or $A.util.removeClass
like so:
Component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
<aura:attribute name="options" type="List"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<div class="slds-dropdown-trigger slds-dropdown-trigger_click slds-is-open" aura:id="myMenu">
<lightning:buttonIcon iconName="utility:down" variant="border-filled" alternativeText="Show More" onclick="{!c.showHide}" onblur="{!c.hideOnBlur}"/>
<div class="slds-dropdown slds-dropdown_left">
<ul class="slds-dropdown__list" role="menu" aria-label="Show More">
<aura:iteration items="{!v.options}" var="item" indexVar="i">
<li class="slds-dropdown__item" role="presentation">
<a href="javascript:void(0);" role="menuitem" tabindex="0">
<span class="slds-truncate" title="{!item.label}">{!item.label}</span>
</a>
</li>
</aura:iteration>
</ul>
</div>
</div>
</aura:component>
Controller JS
({
doInit: function(component, event, helper) {
var options = [
{'label': 'Label1', 'value': 'Value1'},
{'label': 'Label2', 'value': 'Value2'},
{'label': 'Label3', 'value':'Value3'}
];
component.set("v.options", options);
helper.showHide(component, event, helper);
},
showHide : function(component, event, helper){
helper.showHide(component, event, helper);
},
hideOnBlur : function(component, event, helper){
var myMenu = component.find('myMenu');
$A.util.removeClass(myMenu, 'slds-is-open');
},
})
Helper JS
({
showHide : function(component, event, helper){
var myMenu = component.find('myMenu');
$A.util.toggleClass(myMenu, 'slds-is-open');
},
})
Best Answer
You just need to remove the 'slds-is-open' class
template.html
component.js
And then you can open the menu again by doing the same in reverse, i.e: