Reputation: 3362
I'm using mmenu in order to create a nice responsive menu. It works great, but i would like it to open the list item that matches the current url. This way, if you enter the website and open the menu, you can instantly see where you are. I have been trying to use the api in order to achieve this functionality.
See above link for mmenu's api documentation.
My code:
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
var api = $("nav#menu").data("mmenu");
api.bind("openPanel", function($panel) {
console.log("This panel is now opened:" + $panel.attr("id")); //Works
var href = $panel.find("li a").attr("href");
if (href == url) {
api.openPanel($panel); //Open the panel where the matching link is - doesn't work
console.log("Success!" + href);
}
});
I just can't get it to work. Any ideas?
Upvotes: 0
Views: 640
Reputation: 4161
I approached your JS Fiddle a little differently than you originally set it up, so I hope that still works for you.
Mmenu has a configuration object called "classNames" where you can pass a class on the li
that you would like to default to using the "selected" object. Here is your updated mmenu init using this setting:
$("#menu").mmenu({
"offCanvas": {
"zposition": "front"
}
}, {
classNames: {
selected: "current-page"
}
});
What I did prior to calling this init was to loop through the <a>
tags in your menu to match the href with the url variables, then add the class to the parent <li>
when a match was found (note: this uses your existing url var logic).
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$('#menu a').each(function(){
var href = $(this).attr("href");
if ( href == url ){
$(this).parent('li').addClass('current-page');
}
});
On the JS Fiddle, none of the hrefs match the window.location
, so I just hard-coded the class onto one of the third level drawers so you could see it working. When you try this on your setup, you'll obviously want to remove the hard-coded class.
Upvotes: 3