I'm currently using the code below for my sidebar. The issue I'm facing is that the first link in the sidebar always appears active, even when clicking on the second or third links. The other links work as expected, where the active state moves to the clicked link. How can I fix this so that the first link behaves like the others?
document.addEventListener("DOMContentLoaded", function() {
const sidebarWrapper = document.getElementById('sidebar-wrapper');
const closeButton = document.getElementById('close-sidebar');
const currentPath = window.location.pathname;
console.log("Current Path:", currentPath);
document.querySelectorAll('#sidebar .list-group-item').forEach(function(link) {
const linkPath = new URL(link.href).pathname;
console.log("Link Href:", linkPath);
if (currentPath.includes(linkPath)) {
link.classList.add('active');
console.log("Active Link:", link);
}
});
if (closeButton) {
closeButton.addEventListener('click', function() {
if (sidebarWrapper) {
sidebarWrapper.classList.toggle('collapsed');
}
});
} else {
console.error("Close button with ID 'close-sidebar' not found.");
}
});