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.
// Select all anchor elements within the navigation
const navLinks = document.querySelectorAll('.nav-link');
navLinks.forEach(link => {
// Remove any existing "-fill" class
link.classList.remove('bi-house-fill', 'bi-heart-fill', 'bi-envelope-fill');
});
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.
navLinks.forEach(link => {
link.addEventListener('click', () => {
const icon = link.querySelector('i');
const iconClass = icon.classList[1]; // Get the second class (e.g., "bi-house")
icon.classList.toggle(`${iconClass}-fill`);
});
});
Explanation:
- We use
querySelectorAll to select all anchor elements with the class nav-link.
- We loop through each link using
forEach.
- Inside the loop, we use
classList.remove to remove any existing "-fill" classes from the icon within the link. This ensures only one element has the active state.
- We add an event listener to each link for the
click event.
- When a link is clicked, we use
querySelector to get the icon element within the link.
- We then access the second class name of the icon using
classList[1]. This assumes the icon class is the second class on the element.
- Finally, we use
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.