Problem/Motivation
The native JS is good, but, according to the drupal js cashing and another standatrs points I suggest to move it to the drupal standarts of Js. I really respect this approach, but it makes a mess in the future.
Proposed resolution
I did locally some updates
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.menuTree = {
attach: function (context, settings) {
/**
* Add functionality for expanding and collapsing menu tree.
*/
$(once('menu-tree-toggle', '#edit-menu', context)).on('click', 'span.toggle', function(event) {
$($(event.currentTarget)).toggleClass("show");
});
/**
* Set default value of menu tree and expand active branches.
*/
$(once('menu-tree-state', '#edit-menu input[name="menu[menu_parent]"]', context)).each(function (index, element) {
let $item = $('#edit-menu input[name="menu_tree"][value="' + element.value + '"]', context).get(0);
$item.checked = true;
while ($item) {
if ($item.matches('li') && $item.firstElementChild.matches('.toggle')) {
$($item.firstElementChild).addClass("show");
}
$item = $item.parentElement;
}
});
/**
* React on radio button changes and set value of actual menu parent element.
*/
$(once('menu-tree-change', '#edit-menu input[type="radio"][name="menu_tree"]', context)).on('change', function(event) {
$('#edit-menu input[name="menu[menu_parent]"]', context).get(0).value = $(event.currentTarget).val();
});
}
};
})(jQuery, Drupal, drupalSettings);