Changing style of a-tag on click

Viewed 62

I am trying to find a way where when one of the links below is clicked, similarly to the nav-tabs class in Bootstrap, the current link style changes to the active style and the previously clicked link reverts back to normal style. Does Bootstrap 5 have a quick way of changing the style or does it need to be done through normal CSS/JS?

<ul class="nav nav-pills flex-column">
   <li><a class="nav-link link-light" asp-controller="Home" asp-action="Index" asp-route-SortString="Award" asp-route-StatusId="@Context.Request.Query["StatusId"]">Highest Awarded</a></li>
   <li><a class="nav-link link-light" asp-controller="Home" asp-action="Index" asp-route-SortString="Update" asp-route-StatusId="@Context.Request.Query["StatusId"]">Last Updated</a></li>
   <li><a class="nav-link link-light" asp-controller="Home" asp-action="Index" asp-route-SortString="Newest" asp-route-StatusId="@Context.Request.Query["StatusId"]">Date Added (Newest)</a></li>
   <li><a class="nav-link link-light" asp-controller="Home" asp-action="Index" asp-route-SortString="Oldest" asp-route-StatusId="@Context.Request.Query["StatusId"]">Date Added (Oldest)</a></li>
</ul>

So, for instance, if I click on Highest Awarded, the previously clicked link reverts to normal style and Highest Awarded link adds active in its class, thus changing the style to that of active.

2 Answers

$("ul li").on("click",function(){
  $(this).addClass("active").siblings().removeClass("active")
})
.active{
   color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav nav-pills flex-column">
   <li><a class="nav-link link-light" asp-controller="Home" asp-action="Index" asp-route-SortString="Award" asp-route-StatusId="@Context.Request.Query["StatusId"]">Highest Awarded</a></li>
   <li><a class="nav-link link-light" asp-controller="Home" asp-action="Index" asp-route-SortString="Update" asp-route-StatusId="@Context.Request.Query["StatusId"]">Last Updated</a></li>
   <li><a class="nav-link link-light" asp-controller="Home" asp-action="Index" asp-route-SortString="Newest" asp-route-StatusId="@Context.Request.Query["StatusId"]">Date Added (Newest)</a></li>
   <li><a class="nav-link link-light" asp-controller="Home" asp-action="Index" asp-route-SortString="Oldest" asp-route-StatusId="@Context.Request.Query["StatusId"]">Date Added (Oldest)</a></li>
</ul>

This is a simple jquery workaround, you can also implement this using vanilla JS. You can add your required styles for the active class. I don't think we could achieve this only using bootstrap except 5.0. Feel free to comment if you couldn't get it.

Related