Topic: Problem with .active at navigation menu in Wordpress

Dergarcon free asked 5 years ago


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:

window.onload = function() {
 $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');
   }
  }
 }
}

It works untill there are some parameters in the url. Maybe someone has already solved this issue or can improve my code so it will also work if there are parameters in the url.
Thank you very much.
 
Also I would be very thankful if there are some advices or workflow tutorials for using mdb for wordpress. So I could get ahead faster with my development. The tutorials on mdbootstrap.com for wordpress are very helpful. Thank you guys again. 

Mikołaj Smoleński staff answered 5 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



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: 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