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>
