简体   繁体   中英

Prevent bootstrap dropdown closing when clicked anywhere else other than the menu item itself

I need the submenu to be opened when its child is active (as in when the user is on that page). Managed to do so already by this:

// To open active submenu on load
jQuery('.keep-open').find('.current-menu-item').closest('.current-menu-parent').children('.dropdown-toggle').trigger('click');

But upon clicking anywhere, the menu closes. It needs to stay opened unless it's specifically clicked. Only managed to prevent it from closing when clicked outside using this:

// To prevent submenu from being closed on outside click
jQuery('.current-menu-parent').on('hide.bs.dropdown', function() {
  return false;
});

But of course, this seems prevents it from closing too even when the menu itself is clicked. How can I specify it to close only when that menu item is clicked?

Closest reference I found but was this and this but so far still can't get a hold of how to do it. This is on a WordPress site menu via wp_bootstrap_navwalker .

Jsfiddle here

If you want to close only when that menu is clicked just add this code

// Hide dropdown when click menu
jQuery('.current-menu-parent').bind('click', function() {
        $(this).find('ul').fadeOut();
});

Demo here

Or you want to show menu item again when that menu is clicked:

// toggle dropdown when click menu
jQuery('.current-menu-parent').bind('click', function() {
        $(this).find('ul').fadeToggle();
});

Demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM