The following code is used for my sidebar to be able to set the active subpage and properly display the the sidebar when refreshing the page.
It works well if I add the "#" symbol to the href of the subpages but didn't work when changing the href to anything else and removing the "#" symbol. Let's suppose I want to set the href as "/contactpage/. How do I indicate in the below code to choose any href not only the ones that contains the hash symbol?
<script>
(() => {
'use strict'
function setActiveItem() {
const { hash } = window.location
if (hash === '') {
return
}
const link = document.querySelector(`.d-flex a[href="${hash}"]`)
if (!link) {
return
}
const active = document.querySelector('.d-flex .active')
const parent = link.parentNode.parentNode.previousElementSibling
link.classList.add('active')
if (parent.classList.contains('collapsed')) {
parent.click()
}
if (!active) {
return
}
const expanded = active.parentNode.parentNode.previousElementSibling
active.classList.remove('active')
if (expanded && parent !== expanded) {
expanded.click()
}
}
setActiveItem()
window.addEventListener('hashchange', setActiveItem)
})()
</script>
// Select anything with an "href" attribute, regardless of its value
document.querySelectorAll('[href]')
// Select only the first link with the current page's path ("active" link)
const currentPath = window.location.pathname
document.querySelector(`a[href="${currentPath}"]`)
// Select the currently active path including the hash
const currentPathWithHash = window.location.pathname + window.location.hash
document.querySelector(`a[href="${currentPathWithHash}"]`)
To avoid issues when none of the links contain hashes, just remove the first few lines of your code up to const link = ..., which should be replaced by one of the options above (edit to suit your needs).
I also noticed that if active is also the current link, you'll end up first adding the active class to it and deleting it later in your code. Switch the order like this to avoid that:
active.classList.remove('active')
link.classList.add('active')
Note that if there could be more than one link on the page that point to the current path, you should probably add further selectors, like a class name you use for the target links. Unless of course you want to target any link with that path, in which case just use document.querySelectorAll. Yours seem to be under a .d-flex container, so add that to my examples.