0

I'm using this script for my dynamic navbar to set active class. What I want is to set the "home" button to active when you just visit the website and don't have the "index.php" in the url. Is this maybe easier with php?

/*menu handler*/
$(function(){
  function stripTrailingSlash(str) {
    if(str.substr(-1) == '/') {
      return str.substr(0, str.length - 1);
    }
    return str;
  }

  var url = window.location.pathname;
  var activePage = stripTrailingSlash(url);

  $('nav ul li a').each(function(){
    var currentPage = stripTrailingSlash($(this).attr('href'));

    if (activePage == currentPage) {
      $(this).parent().addClass('active');
    }
  });
});
Mikkel
  • 50
  • 1
  • 9
  • Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Machavity Mar 31 '16 at 20:35
  • try `var currentPage = stripTrailingSlash($(this).attr('href')) || "index.php";` which replaces an empty path (`"/"` without the trailing slash) with `index.php` so that your href compare works. yes, php might be simpler, and it would work from pageload and w/o JS... – dandavis Mar 31 '16 at 20:36
  • That did not work. Take a look for yourself: https://mkhosting.kohlercoding.dk/ – Mikkel Mar 31 '16 at 20:42
  • oops, make it: `var activePage = stripTrailingSlash(url) || "/index.php";`, i had the default in the wrong slot... tested. – dandavis Mar 31 '16 at 20:45
  • That worked. Thanks. Can you post it as an answer so I can mark it answered? – Mikkel Mar 31 '16 at 20:52

0 Answers0