Showing 1 – 1 of 1 replies
Bob

For the STATIC HTML option, is there […]

Bob PURCHASED
3 years ago
Hi,

For the STATIC HTML option, is there any way to have the navigation set the active link in the nav tree, based on the current URL? I found this, but it needs tweaking:

$(function () {
setNavigation();
});

function setNavigation() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);

$(".nav a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).closest('li').addClass('active');
}
});
}

The final result should of course be able to handle multiple sub menus as well. Would be grateful if you could complete the script?
omadmin
omadmin SELLER
3 years ago
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>