[wp-trac] [WordPress Trac] #31218: nav-menu.js menu item added event
WordPress Trac
noreply at wordpress.org
Mon Dec 11 20:03:44 UTC 2023
#31218: nav-menu.js menu item added event
------------------------------------+------------------------------
Reporter: welcher | Owner: adamsilverstein
Type: enhancement | Status: closed
Priority: normal | Milestone: 4.8
Component: Menus | Version: 4.2
Severity: trivial | Resolution: fixed
Keywords: has-patch next-release | Focuses: javascript
------------------------------------+------------------------------
Comment (by harishaas):
You can manually trigger a custom JavaScript event after you've added your
menu item. You would need to modify your plugin to dispatch this event
after adding the item, and then you can listen for this event in your
custom JavaScript code. Here's an example:
javascript
{{{
// Inside your plugin code after adding the menu item
var event = new Event('menu-item-added');
document.dispatchEvent(event);
}}}
In your custom JavaScript code, you can listen for this event:
javascript
{{{
document.addEventListener('menu-item-added', function (event) {
// Handle the event here
});
}}}
Mutation Observer: You can use a MutationObserver to watch for changes in
the DOM and react when a new menu item is added. This approach is more
generic and doesn't rely on custom events. Here's a basic example:
javascript
{{{
var menuList = document.querySelector('.menu');
var observer = new MutationObserver(function (mutationsList) {
for (var mutation of mutationsList) {
if (mutation.type === 'childList') {
// A child node (menu item) was added
// Handle the added menu item here
}
}
});
}}}
observer.observe(menuList, { childList: true });
This code will trigger whenever a new menu item is added to the menu list,
allowing you to react to the addition.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/31218#comment:38>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list