mmenu wordpress plugin - bind open / close events

124 Views Asked by At

I am using the licenced wordpress plugin version 3.1.0.

I have the menu working, but I cannot access the mmenu API to trigger the button open / close effect I would like to use. Previously I have used the mmenu core version [not WP plugin] and triggered the class changes using this:

var $menu = $("#menu").mmenu({...})
var API = $menu.data("mmenu");
API.bind("open:finish", function () {
    $("#menu-btn").addClass("is-active");
});
API.bind("close:finish", function () {
    $("#menu-btn").removeClass("is-active");
});

Modifying the var API to use the plugin generated id fails with undefined, probably because the menu creation is managed in a different script.

var API = $('#mm-1').data("mmenu"); //'mm-1' - the plugin generated mmenu id

I have also tried to use jQuery direct on #menu-btn but it is not triggered unless I remove the #menu-btn from the mmenu settings. For example [not copied, just a rough example so please ignore syntax errors]:

$("#menu-btn").click(function(){console.log('click')});

all I need is to add / remove an 'is-active' class to the open menu link [id=menu-btn].

1

There are 1 best solutions below

0
ice70 On

The mmenu adds a body class when opened, so added a mutation observer to check if the has the .mm-wrapper--opened class or not. If it does, add the 'is-active' class to the menu icon (which uses the .hamburger class) and if not, remove it.

if ($('body').hasClass('mm-wrapper--opened')){
  $('.hamburger').addClass("is-active");
}
        
const targetNode = document.body;
const config = { childList : true, attributes: true };
        
const callback = function(mutationsList, observer) {
  for(let mutation of mutationsList) {
    if (mutation.type === 'attributes') {
      if ($('body').hasClass('mm-wrapper--opened')){
        setTimeout(() => {  $('.hamburger').addClass("is-active"); }, 500);
      }
      else {
        $('.hamburger').removeClass("is-active");
      }
    }
  }
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);