I have a navbar with Bootstrap icon inside the anchor tags
Here’s my code:
<li class="nav-item">
<a href="#" class="nav-link">
<i class="bi bi-house"></i>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="bi bi-heart"></i>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="bi bi-envelope"></i>
</a>
</li>
I want to add -fill
if it clicked, and remove it when clicking on another navigation. I’ve tried classList.toggle
, but is seems just adding new class without appending it.
<li class="nav-item">
<a href="#" class="nav-link">
<i class="bi bi-house-fill"></i>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="bi bi-heart"></i>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="bi bi-envelope"></i>
</a>
</li>
2
Answers
The issue with your current approach is that classList.toggle only adds the class if it’s not present and removes it if it is. This means it will only switch between the original class and the class with "-fill" appended, not allowing multiple elements to have the "-fill" class simultaneously.
Here’s how you can achieve the desired behavior:
1. Remove existing "-fill" classes:
Before adding the "-fill" class to the clicked element, you need to remove it from any other element that might have it. This ensures only one element has the active state at a time.
2. Add "-fill" class to the clicked element:
Now, when an anchor element is clicked, you can use classList.toggle to add the "-fill" class specific to the clicked icon.
Explanation:
querySelectorAll
to select all anchor elements with the class nav-link.forEach
.classList.remove
to remove any existing "-fill" classes from the icon within the link. This ensures only one element has the active state.click
event.querySelector
to get the icon element within the link.classList[1]
. This assumes the icon class is the second class on the element.classList.toggle
with a template literal to dynamically construct the class name to be toggled. This ensures the appropriate "-fill" class is added or removed based on the clicked icon.This approach ensures that only the clicked icon has the "-fill" class, providing the desired visual feedback for the active navigation item.
To achieve the behaviour you’re looking for, you’ll need to add event listeners to your anchor tags. When an icon is clicked, you should add
-fill
to its class if it’s not already there, and for all other icons, you should remove-fill
if it’s present.For this purpose, you should do as follows:
Array#forEach
to map through yournavlinks
, get the<i>
classes, andreplace
the-fill
with an empty string.-fill
to the clicked element if it already doesn’t have it.Here is a working example: