Currently, I am exploring ways to come up with a more sophisticated solution. However, my proficiency in jquery is somewhat limited at the moment.
I believe there must be a more efficient method to achieve the desired function outlined below. In essence, I am attempting to alter the background of the parent element upon clicking.
As it stands now, I simply add a class and remove any other potential classes from the other buttons.
Relevant HTML:
<div class="panel panel-widget widget-latest-posts">
<div class="panel-heading">
<h3 class="widget-title">Also worth reading</h3>
</div>
<div class="panel-body">
<div class="btn-pref btn-group btn-group-justified btn-group" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" id="btn-popular-posts" class="btn btn-popular-posts" href="#tab1" data-toggle="tab"><i class="fa fa-fire"></i>
<span class="hidden-xs">Popular</span>
</button>
</div>
<div class="btn-group" role="group">
<button type="button" id="btn-latest-posts" class="btn btn-latest-posts" href="#tab2" data-toggle="tab"><i class="fa fa-clock-o"></i>
<span class="hidden-xs">New</span>
</button>
</div>
<div class="btn-group" role="group">
<button type="button" id="btn-popular-comments" class="btn btn-popular-comments" href="#tab3" data-toggle="tab"><i class="fa fa-commenting-o"></i>
<span class="hidden-xs">Active</span>
</button>
</div>
</div>
Relevant CSS:
.bpp-toggled {
background: orange !important;
}
.blp-toggled {
background: lime !important;
}
.bpc-toggled {
background: purple !important;
}
Jquery
$("#btn-popular-posts").click(function() {
$('.widget-latest-posts').addClass('bpp-toggled');
$('.widget-latest-posts').removeClass('blp-toggled');
$('.widget-latest-posts').removeClass('bpc-toggled');
});
$("#btn-latest-posts").click(function() {
$('.widget-latest-posts').addClass('blp-toggled');
$('.widget-latest-posts').removeClass('bpp-toggled');
$('.widget-latest-posts').removeClass('bpc-toggled');
});
$("#btn-popular-comments").click(function() {
$('.widget-latest-posts').addClass('bpc-toggled');
$('.widget-latest-posts').removeClass('blp-toggled');
$('.widget-latest-posts').removeClass('bpp-toggled');
});
If you can suggest a better and more elegant solution or perhaps provide keywords for further research, I would greatly appreciate it. Currently, maintaining this code will become increasingly difficult as I add more buttons.
Thank you for your assistance!
Edit: I have tried using toggleClass, but it did not work as expected in this scenario. It simply removed the class on the second click.