Topic: Problem with .active at navigation menu in Wordpress
I am using mdb (jquery) for wordpress. I am facing the following problem with the navigation menu:
I copied one of the mdbootstrap navs as html-code into my header.php.
The active class of the nav-item is not switching based on the page i am on. Do you have some sort of (js-)code to fix this issue?
I wrote the following code to try to fix the problem:
$url = window.location.href;
$links = document.querySelectorAll(".nav-link");
$home = 'https://'+window.location.hostname+'/';
$('.nav-item').removeClass('active');
if ($url == $home) {
$home_link = document.querySelector('a[href="/"]');
$home_link.parentElement.classList.add('active');
} else {
for ($i = 1; $i < $links.length; $i++) {
if($url.startsWith($links[$i])){
$links[$i].parentElement.classList.add('active');
}
}
}
}
Mikołaj Smoleński staff answered 6 years ago
Hello Dergarcon,
This is kind of a tricky issue. In my opinnion, the best solution is to copy navbar to each page and add .active class to the corresponding nav item in each page. Then, while opening one of the subpages the correct item will have .active class. The problem will be solved without using JS.
If You can't make it like this, please write me back here and I'll try to prepare the jQuery code for You.
Best regards
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Free
- Premium support: No
- Technology: MDB jQuery
- MDB Version: 4.5.15
- Device: All
- Browser: All
- OS: All
- Provided sample code: No
- Provided link: No