Dynamic Hierarchical Menu Builder In JavaScript – Menu Editor

Category: Javascript , Menu & Navigation | November 24, 2023
Author:davicotico
Views Total:452 views
Official Page:Go to website
Last Update:November 24, 2023
License:MIT

Preview:

Dynamic Hierarchical Menu Builder In JavaScript – Menu Editor

Description:

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 and Delete 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
  }
});

10. Set the maximum number of menu levels.

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

You Might Be Interested In:


Leave a Reply