Home > front end >  Add active class to link with current page
Add active class to link with current page

Time:02-16

I'm trying to add a class to all the links of the various menus on the page, in order to activate the active state when the relative page is loaded.

HTML

<div id = "content">
  ...
  <div class = "menu-item">
    <a href="/page1/" > Page1 </a>
  </div>
  ...
</div>

JS

<script>
  jQuery (function ($) {
      var pgurl = window.location.href.substr (window.location.href.lastIndexOf ("/")   1);
        $ (". menu-item> a"). each (function () {
        if ($ (this) .attr ("href") == pgurl || $ (this) .attr ("href") == '')
        $ (this) .addClass ("active");
        // $ (this) .parent ("li"). addClass ("active");
      })
  });
</script>

I've tried other scripts too but they don't work.

I believe the problem is related to the HREF URL.

In HTML, I pass a value like / page1 / but in WordPress, the correct permalink is / parent / page1 /.

How can I fix and improve the script?

CodePudding user response:

You can test this code with your real urls.

Retrieving the last valid "word" (in \abc\page1 is page1 or in \xyz\page1\ is page1) for both url, page and menu item url. Finally I make the comparison between the two.

One more thing that would be done, remove any hashes (url\page#abc) and parameters (url\page?Param=value)

jQuery(function($) {
  var window_location_href = 'http://your.site.com/parent/page2/';
  window_location_href = window_location_href.endsWith('/') ? window_location_href.substr(0, window_location_href.length - 1) : window_location_href;
  var pgurl = window_location_href.substr(window_location_href.lastIndexOf("/")   1);


  $(".menu-item > a").each(function() {
    var thisPage = $(this).attr("href");
    thisPage = thisPage.endsWith('/') ? thisPage.substr(0, thisPage.length - 1) : thisPage;
    thisPage = thisPage.substr(thisPage.lastIndexOf("/")   1);

    if (thisPage == pgurl)
      $(this).addClass("active");
  });

});
.menu-link {
  color: blue;
  display: block;
}

.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="content">
  ...
  <div >
    <a href="/complexPath/parent/page1/" > Page1 </a>
    <a href="/complexPath/parent/page2/" > Page2 </a>
    <a href="/complexPath/parent/page3/" > Page3 </a>
  </div>
  ...
</div>

EDIT

To be more clear, the real end code will be this:

jQuery(function($) {
  var window_location_href = window.location.href;
  window_location_href = window_location_href.endsWith('/') ? window_location_href.substr(0, window_location_href.length - 1) : window_location_href;
  var pgurl = window_location_href.substr(window_location_href.lastIndexOf("/")   1);


  $(".menu-item > a").each(function() {
    var thisPage = $(this).attr("href");
    thisPage = thisPage.endsWith('/') ? thisPage.substr(0, thisPage.length - 1) : thisPage;
    thisPage = thisPage.substr(thisPage.lastIndexOf("/")   1);

    if (thisPage == pgurl)
      $(this).addClass("active");
  });

});

CodePudding user response:

According to Wordpress Code reference page: wp_nav_menu()#menu-item-css-classes, the class below is added to menu items that correspond to the currently rendered page.

  • .current-menu-item

So, basically what you can do is to just add the corresponding css for the class names which are automatically generated by wordpress:

.current-menu-item {
    color: red; // change the color of the current active page to #red;
}
.current-menu-parent {
    // current active menu's parent styles
}

You don't need to use jQuery.

CodePudding user response:

Please try:

<script>
  jQuery(function($){  var cururl = window.location.href;                
  const urlarray = cururl.split("/");
var last = urlarray[urlarray.length-2]);
      
        $(".menu-item> a").each(function() {
       var pageurl = $(this).attr("href"); if(pageurl.indexOf(last) > -1){
        $(this).addClass("active");
        // $ (this).parent ("li").addClass ("active"); }
      })
  });
</script>
  • Related