I am displaying a set of button group listed from 1 to 5, highlighting button 1
after my jQuery library has been loaded. Once the next button is clicked, i am changing the button group from 6 to 10, and would like to highlight button 8
which is not happening in my case.
Lightning Component
<aura:component >
<ltng:require scripts="{!$Resource.jQueryLib + '/js/jquery-3.1.1.min.js'}"
afterScriptsLoaded="{!c.afterScriptsLoaded}"/>
<aura:attribute name="pageNumberList" type="List"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<div class="slds-button-group" role="group">
<aura:iteration items="{!v.pageNumberList}" var="pageNum">
<button class="slds-button slds-button--neutral"
id="{!pageNum.value}"
onclick="{!c.offsetChanged}">
{!pageNum.value}
</button>
</aura:iteration>
<button class="slds-button slds-button--neutral"
onclick="{!c.nextPageClicked}">Next</button>
</div>
</aura:component>
Controller
doInit : function(component, event, helper)
{
var numberList = [];
for(var i=1;i<6;i++)
{
numberList.push({
value:i
});
}
component.set("v.pageNumberList", numberList);
},
afterScriptsLoaded:function(component, event, helper){
jQuery("#1").removeClass("slds-button--neutral").addClass("slds-button--brand activeBlue");
},
nextPageClicked:function(component, event, helper)
{
var numberList = [];
for(var i=6;i<11;i++)
{
numberList.push({
value:i
});
}
component.set("v.pageNumberList", numberList);
//**This step is executing but not shown on the DOM**//
jQuery("#8").removeClass("slds-button--neutral").addClass("slds-button--brand activeBlue");
console.log(jQuery("#8").attr("class"));
}
Interesting fact
console.log
statement at the last line of code prints slds-button--brand activeBlue
.
I understand that the component.set
resetting my button group to its initial state, but why is my jQuery.removeClass()
method executing but not rendering on the DOM?
Best Answer
You should be using the built in
A
api provided by Lightning.To add or remove a class, call something like this:
However, I can see that you would need DYNAMIC ids for this, which means you can't use
aura:id
There is another way though - use the source list to provide the styling.
In the init method, call this:
Now remove the
afterScriptsLoaded
method, as it's all encapsulated in the init method.In after this, your can just call a generic setter/unsetter for these classes:
Then, in your iteration, just append the class to what is there: