简体   繁体   中英

Fail Add Active Navigation Class Based on URL

I have a basic menu structure on my blog using code below. I've tried every snipped and also doing some of similar topics here but nothing works. All I want to do is to add active class to my navigation menu based on url. So the visitors or user on the website knows on which page or part of the site he is on. So, can someone please explain simply where and how to add in javascript to do this ?

Menu structure

<div id="navigation">
<div class="backer" style="position: relative;">
<div class="header-inner-wrap">
<div class="header section" id="header">
<div class="widget Header" data-version="1" id="Header1">
<h1><div id="header-inner">
<a href=""></a></div></h1>
</div></div>
</div>
<nav class="main-nav" itemscope="itemscope" role="navigation">
<ul class="menu">
<li><a href="">About</a></li>
<li><a href="">Tutorial</a></li>
<li><a href="">Tips</a></li>
</ul>
</nav>
</div>
</div>

Javascript:

$(function() {
     var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
     $("menu li a").each(function(){
          if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
          $(this).addClass("active");
     })
});

CSS:

.menu li .active{border-bottom:3px blue solid;}

Thanks in advance

You may want to check that your selector for menu class is matching something:

$("menu li a").each(function(){

ahould be

$(".menu li a").each(function(){

EDIT: Based on new information, the following change should fix your problem.

Change from

var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);

to

var pgurl = window.location.href;

And the or part of your condition is unnecessary. So change from this

$("menu li a").each(function(){
      if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
      $(this).addClass("active");
 })

to this

$(".menu li a").each(function(){
      if($(this).attr("href") == pgurl){
          $(this).addClass("active");
      }
 });

Apart from this solving your immediate problem, you should endeavour to learn javascript properly instead of copying and using snippets, so you can easily analyze your code and detect the cause of your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM