Collapsible Submenus in the Divi Mobile Menu
Folds submenus in Divi's mobile menu and adds a plus/minus button to open each one, so long menus no longer fill several screens on phones.
Opens WPIDE on
Code
<style>
.et_mobile_menu .menu-item-has-children{position:relative;}
.et_mobile_menu .menu-item-has-children > .sub-menu{display:none!important;padding-left:0;}
.et_mobile_menu .menu-item-has-children.wpide-open > .sub-menu{display:block!important;}
.et_mobile_menu .menu-item-has-children > a{padding-right:56px;}
.wpide-divi-subtoggle{position:absolute;top:4px;right:4px;width:40px;height:40px;border:0;border-radius:4px;background:rgba(0,0,0,.05);font-size:20px;line-height:1;cursor:pointer;color:inherit;}
</style>
<script>
(function () {
function setup(menu) {
if (menu.getAttribute('data-wpide-toggles')) { return; }
menu.setAttribute('data-wpide-toggles', '1');
menu.querySelectorAll('.menu-item-has-children').forEach(function (item) {
var button = document.createElement('button');
button.type = 'button';
button.className = 'wpide-divi-subtoggle';
button.setAttribute('aria-expanded', 'false');
button.setAttribute('aria-label', 'Show submenu');
button.textContent = '+';
button.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
var open = item.classList.toggle('wpide-open');
button.setAttribute('aria-expanded', open ? 'true' : 'false');
button.textContent = open ? '−' : '+';
});
item.insertBefore(button, item.querySelector('.sub-menu'));
});
}
function scan() { document.querySelectorAll('.et_mobile_menu').forEach(setup); }
window.addEventListener('load', scan);
document.addEventListener('click', function (e) {
if (e.target.closest && e.target.closest('.mobile_menu_bar, .mobile_nav')) { setTimeout(scan, 50); }
});
})();
</script>
Notes
Works with the default Divi header and the Divi Theme Builder menu module.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.