I have not tried it, but try the following script:
const currentLinkParents = currentLink => { let target = currentLink let parent = [] while (target) { // Get only nav-link if (target.classList.contains('nav-item')) parent.unshift(target.querySelector('.nav-link')) // Stop on treeview if (target.classList.contains('treeview')) break target = target.parentNode } return parent } const updateMenu = currentLink => { document.querySelectorAll('#menu .active').forEach(i => i.classList.remove('active', 'show'))
for (const i of currentLinkParents(currentLink)) { i.classList.add('active') i.classList.contains('treeview-toggle') && i.classList.add('show') } } updateMenu(document.querySelector(`#menu a[href="${window.location.pathname.split('/').pop()}"]`))
make sure its menu using id = "menu" <ul class="nav treeview mb-4" id="menu" data-accordion>
It almost works! It sets active on all the menus (Main, sub) but not on the actual link.
So if I have for example the following menu:
Menu 1 Submenu 1.1 LinkToPage
Then Menu 1 and Submenu 1.1 is active and expanded, but the actual LinkToPage is not set to active. Have tried to fix it, but can't figure it out. Javascript is NOT my strong point. Please let me know if you can find a solution?
I have not tried it, but try the […]
const currentLinkParents = currentLink => {
let target = currentLink
let parent = []
while (target) {
// Get only nav-link
if (target.classList.contains('nav-item')) parent.unshift(target.querySelector('.nav-link'))
// Stop on treeview
if (target.classList.contains('treeview')) break
target = target.parentNode
}
return parent
}
const updateMenu = currentLink => {
document.querySelectorAll('#menu .active').forEach(i => i.classList.remove('active', 'show'))
for (const i of currentLinkParents(currentLink)) {
i.classList.add('active')
i.classList.contains('treeview-toggle') && i.classList.add('show')
}
}
updateMenu(document.querySelector(`#menu a[href="${window.location.pathname.split('/').pop()}"]`))
make sure its menu using id = "menu"
<ul class="nav treeview mb-4" id="menu" data-accordion>
It almost works! It sets active on all the menus (Main, sub) but not on the actual link.
So if I have for example the following menu:
Menu 1
Submenu 1.1
LinkToPage
Then Menu 1 and Submenu 1.1 is active and expanded, but the actual LinkToPage is not set to active. Have tried to fix it, but can't figure it out. Javascript is NOT my strong point. Please let me know if you can find a solution?
document.querySelector(`#menu a[href="${window.location.pathname.split('/').pop()}"]`).classList.add('active');
This will mark the current page in the menu as "active", and thus selected/highlighted.