How to Apply and Remove Styles with button using toggle in Lightning Compoment

By | November 13, 2019

Lightning Component

<aura:component >
    <span aura:id="sfc" >SalesforceCodes</span><br/><br/><br/><br/>
    <lightning:button label="Add Style" onclick="{!c.addstyle}"/>
    <lightning:button label="Remove Style" onclick="{!c.Removestyle}"/>
    <lightning:button label="toggle" onclick="{!c.Toggle}"/>
</aura:component>

Controller Js

({
	addstyle : function(component, event, helper) {
        var targetcmp=component.find("sfc");
        $A.util.addClass(targetcmp,'external');
	},
    Removestyle : function(component, event, helper) {
        var targetcmp=component.find("sfc");
        $A.util.removeClass(targetcmp,'external');
    },
    Toggle : function(component, event, helper) {
        var targetcmp=component.find("sfc");
        $A.util.toggleClass(targetcmp,'external');
    }
})

Css Styles

.THIS.external {
    color:white;
    background-color:green;
}

Application

<aura:application extends="force:slds" >
    <c:Basic2 />
</aura:application>

Output

Adding Styles by clicking on Add Style button
Style removed by clicking on Remove style or toggle button
Share this...
Share on Facebook
Facebook
Email this to someone
email

Leave a Reply

Your email address will not be published. Required fields are marked *