Search code examples
phpjquery.htaccess

Active Menu not working after trailing Slash added in .htaccss


I’m creating a dynamic PHP blog site, where I have active current menu by using jQuery, everything was works fine before .htaccess modification for trailing slash…

link activated

enter image description here

Tech is tab and contain is activated but not working Active Menu LInk

enter image description here

If you visit below url Menu Active Link works fine

 http://example.com/tech

If you visit below url than Menu Active Link will not work

http://example.com/tech/

For Trailing Slash I have use below code

.htaccess

#force trainling slash
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
#end of force trailing slash

RewriteRule ^([0-9a-zA-Z]+)/?$ archive.php?category=$1 [QSA,L]

Menu

<ul id="nav-main">
  <li><a href="http://example.com/"> Home</a></li>
  <li><a href="/tech">  Technology</a></li> 
  <li><a href="/business">Business</a></li>
  <li><a href="/sports"> Sports</a></li> 
  <li><a href="/science">Science</a></li>
</ul>

jQuery

jQuery(document).ready(function($){
        var path = window.location.href;
        $('#nav-main li a').each(function() {
            if (this.href === path) {
                $(this).addClass('active'); 
            }
        });
    });

Css

ul#nav-main li a:hover {
  border-bottom: 4px solid #4db2ec;
  color: black;
  font-weight: bold;
}
ul#nav-main li a.active {
  border-bottom: 4px solid #4db2ec;
  color: black;
  font-weight: bold;
}

N.B.: The contain of the website works fine.... only ACTIVE Link not working (main problem).


Solution

  • Try to add this in your if : || this.href === path + '/'

    jQuery(document).ready(function($){
        var path = window.location.href;
        
        console.log(path);
        $('#nav-main li a').each(function() {
            if (this.href === path || this.href === path + '/') {
                $(this).addClass('active'); 
            }
        });
    });
    ul#nav-main li a:hover {
      border-bottom: 4px solid #4db2ec;
      color: black;
      font-weight: bold;
    }
    ul#nav-main li a.active {
      border-bottom: 4px solid #4db2ec;
      color: black;
      font-weight: bold;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul id="nav-main">
      <li><a href="http://example.com/"> Home</a></li>
      <li><a href="/tech">  Technology</a></li> 
      <li><a href="/business">Business</a></li>
      <li><a href="/sports"> Sports</a></li> 
      <li><a href="/science">Science</a></li>
      <li><a href="/js/">Test</a></li>
    </ul>