mmenu help - how to add "Selected" class to current page (maybe using "currentItem" addon)

1.7k views Asked by At

I'm using mmenu to create a menu. While I'm open to advice on whether to use jquery or PHP (best practice advice), I need to be able to easily include my menu on each new page. I hope this makes updates easier.

The problem is that mmenu does not seem to automatically activate the active li on page load. Once a link to a new page is clicked, the li appears selected, but once the new page loads and the scripts start over and I arrive at the main menu. The issue might be further complicated by the fact that I have submenus.

I have tried using the 3rd party "currentitem" addon for mmenu with no success.

This is a simplified menu example.

<nav id="menu">
<li>
   <ul>
      <li><a href="/root/page1.html">page1</a></li>
      <li>
          <ul>
               <li><a href="/root/page2.html">page2</a></li>
               <li><a href="/root/page3.html">page3</a></li>
          </ul>
      </li>
   </ul>
</ul>
</nav>
2

There are 2 answers

0
Derek Buntin On

You need to add the class 'mm-selected' to the parent li tag for the active href, this will make your menu open at the correct position.

<nav id="menu">
<li>
   <ul>
      <li class="mm-selected"><a href="/root/page1.html">page1</a></li> <-- this will be highlighted and will open the sub menu below.
      <li>
          <ul> <-- this sub menu will show when the parent is selected
               <li><a href="/root/page2.html">page2</a></li>
               <li><a href="/root/page3.html">page3</a></li>
          </ul>
      </li>
   </ul>
</ul>
</nav>

I hope this helps.

Derek

0
GreatBlakes On

If I'm understanding the question correctly, I'd just loop through the <a> tags until you find a match with window.location.href.indexOf(href). If you have a really big menu, I'm sure someone else here may recommend a more optimized solution- maybe prepping the class using PHP would be better in that case.

$('#menu a').each(function(){
    var href = $(this).attr('href');

    if ( window.location.href.indexOf(href) >= 0 ){
        $(this).parent('li').addClass('current-page');
    }
});

Then after that, init Mmenu with the current-page class set to the classNames configuration for selected.

$("#menu").mmenu({
    //Options        
    "offCanvas": {
        "zposition": "front" //Just an example option
    }
}, {
    //Configuration
    classNames: {
        selected: "current-page" //Change this class to match the default li you want
    }
});

Here's a Fiddle.