Home > other >  Add css class to menu item based on current url
Add css class to menu item based on current url

Time:08-06

I have menu and I want to add css class to menu item based on current url

I try to use jQuery but this code add current-active-menu css class only to a href="https://mywebsite.com/dashboard/ element

jQuery(document).ready(function() {
  if (window.location.href.indexOf("https://mywebsite.com/dashboard/") > -1) {
    $('a[href="https://mywebsite.com/dashboard/"]').addClass("current-active-menu");
  }
});

jQuery(document).ready(function() {
  if (window.location.href.indexOf("https://mywebsite.com/dashboard/?candidate-page=resumes-list") > -1) {
    $('a[href="https://mywebsite.com/dashboard/?candidate-page=resumes-list"]').addClass("current-active-menu");
  }
});

jQuery(document).ready(function() {
  if (window.location.href.indexOf("https://mywebsite.com/dashboard/?candidate-page=my-orders") > -1) {
    $('a[href="https://mywebsite.com/dashboard/?candidate-page=my-orders"]').addClass("current-active-menu");
  }
});

CodePudding user response:

You should use an else if and put https://mywebsite.com/dashboard/ at the end because it would match your other 2:

jQuery(document).ready(function() {
  if (window.location.href.indexOf("https://mywebsite.com/dashboard/?candidate-page=my-orders") > -1) {
    $('a[href="https://mywebsite.com/dashboard/?candidate-page=my-orders"]').addClass("current-active-menu");
  } else if (window.location.href.indexOf("https://mywebsite.com/dashboard/?candidate-page=resumes-list") > -1) {
    $('a[href="https://mywebsite.com/dashboard/?candidate-page=resumes-list"]').addClass("current-active-menu");
  } else if (window.location.href.indexOf("https://mywebsite.com/dashboard/") > -1) {
    $('a[href="https://mywebsite.com/dashboard/"]').addClass("current-active-menu");
  }
});

Also it looks like you whole url should match so you should think about using === in your if instead of indexOf:

window.location.href === "https://mywebsite.com/dashboard/?candidate-page=my-orders"

With your original problem, using indexOf put the active class onto the wrong link because you were testing if that string exists anywhere in the url (which https://mywebsite.com/dashboard/ exists in all three of your urls you test)

  • Related