Dynamic Hierarchical Menu Builder In JavaScript – Menu Editor

Category: Javascript , Menu & Navigation | February 17, 2025
Authordavicotico
Last UpdateFebruary 17, 2025
LicenseMIT
Tags
Views731 views
Dynamic Hierarchical Menu Builder In JavaScript – Menu Editor

Menu Editor is a JavaScript library that provides an interactive interface for building and managing multi-level menus.

You can reorder menu items, delete items, update content, and export the final menu structure as JSON.  Great for CRUD apps, CMS sites, dashboards, and any project needing customizable menus.

How to use it:

1. Download the package and import the Menu Editor into your project.

// ES Module
import '@davicotico/menu-editor/lib/css/styles.css';
import { MenuEditor } from '@davicotico/menu-editor';
// Browser
<link rel="stylesheet" href="dist/styles.min.css" />
<script src="dist/menu-editor.js"></script>

2. Create an empty container to hold the menu editor.

<div id="demo"></div>

3. Initialize the menu editor with default options.

const menuEditor = new MenuEditor('demo');

4. Populate the menu with your preset items.

var myData = [
  {
  "text": "Home",
  "href": "#",
  "tooltip": "Home Page",
  "icon": "Icon Class(es) Here",
  "children": []
  },
  {
  "text": "JavaScript",
  "href": "#",
  "tooltip": "JavaScript",
  "icon": "Icon Class(es) Here",
  "children": [
    {
    "text": "React",
    "href": "#",
    "tooltip": "React",
    "icon": "Icon Class(es) Here",
    "children": []
    },
    {
    "text": "Angular",
    "href": "#",
    "tooltip": "Angular",
    "icon": "Icon Class(es) Here",
    "children": []
    }
  ]
  }
];
menuEditor.setArray(myData);

5. Mount the menu editor.

menuEditor.mount();

6. Output the menu strucrure as JSON.

let output = menuEditor.getString();

7. Add a new item to the menu.

let vueItem = {
    "text": "Vue",
    "href": "#",
    "tooltip": "Vue",
    "icon": "Icon Class(es) Here",
    "children": []
};
menuEditor.add(vueItem);

8. Update an item.

let newData = {
    "text": "Vue",
    "href": "#",
    "tooltip": "Vue",
    "icon": "Icon Class(es) Here",
};
menuEditor.update(vueItem);

9. Handle the Edit, Delete, and DragEnd events.

menuEditor.onClickEdit((event) => {
  let itemData = event.item.getDataset();
  console.log(itemData);
  menuEditor.edit(event.item);
  alert('Update Item!')
});
menuEditor.onClickDelete((event) => {
  if (confirm('Do you want to delete the item ' + event.item.getDataset().text)) {
    event.item.remove(); // remove the item
  }
});
menuEditor.onDragEnd((event) => {
  let output = editor.getString();
  console.log(output);
  // add logic here
});

10. Set the maximum number of menu levels.

const menuEditor = new MenuEditor('demo',{
      maxLevel: 3
});

Changelog:

v1.2.0 (02/17/2025)

  • feat: Added a new onDragEnd event to handle the end of drag interactions

You Might Be Interested In:


Leave a Reply