Activity Forums Salesforce® Discussions How to use $A.util.toggleClass in Salesforce Lightning Components?

  • Avnish Yadav

    Member
    July 30, 2018 at 1:44 pm

    Hello Anjali,

    We use $A.util.toggleClass to add or remove a CSS style on a component or element during runtime.

    To retrieve the class name on a component, use component.find('myCmp').get('v.class'), where myCmp is the aura:idattribute value.

    To append and remove CSS classes from a component or element, use the $A.util.addClass(cmpTarget, 'class') and $A.util.removeClass(cmpTarget, 'class') method

    Thanks.

  • Parul

    Member
    September 23, 2018 at 8:56 am

    To change styles dynamically, use $A.util.toggleClass() or $A.util.addClass(),$A.util.removeClass().
    Use $A.util.toggleClass() for component instead of a DOM element.

    //toggleCss.cmp
    <aura:component>
       <div aura:id=”changeIt”>Change Me!</div><br />
       <ui:button press=”{!c.applyCSS}” label=”Add Style” />
       <ui:button press=”{!c.removeCSS}” label=”Remove Style” />
    </aura:component>
    
    //toggleCssController.js
    ({
       applyCSS: function(cmp, event) {
          var cmpTarget = cmp.find(‘changeIt’);
          $A.util.addClass(cmpTarget, ‘changeMe’);
       },
       removeCSS: function(cmp, event) {
          var cmpTarget = cmp.find(‘changeIt’);
          $A.util.removeClass(cmpTarget, ‘changeMe’);
       }
    })
    
    //toggleCss.css
    .THIS.changeMe {
        background-color:yellow;
        width:200px;
    }

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos