Lightweight Custom Context Menu In Vanilla JavaScript – contextMenu.js

Category: Javascript , Menu & Navigation | November 19, 2021
Author:mboussaid
Views Total:54 views
Official Page:Go to website
Last Update:November 19, 2021
License:MIT

Preview:

Lightweight Custom Context Menu In Vanilla JavaScript – contextMenu.js

Description:

A lightweight context menu JavaScript library that allows you to bind any actions to menu items.

How to use it:

1. Import the contextmenu.js into your document.

<script src="./src/contextMenu.min.js" ></script>

2. Define an array of menu items as follows:

const menuItem = [
      {
        template: "<span>Menu Item 1</spa>",
        onClick : function(){
          // do something
        }
      },
      {
        template: "<span>Menu Item 2</spa>",
        onClick : function(){
          // do something
        }
      },
      {
        template: "<span>Menu Item 3</spa>",
        onClick : function(){
          // do something
        }
      },
]

3. Initialize the context menu and attach it to the target element you specify.

contextMenu({
  items: menuItems
}).init(document.getElementById("myContainer"));

4. Apply your own CSS styles to the context menu.

.contextMenu{
  background-color: #7d5fff;
}

.contextMenuItem{
  transition: all 0.4s ease;
  display: flex;
  justify-content: center;
  align-items: center;
  align-content: center;
  padding: 10px;
  color:#fff;
}

.contextMenuItem:hover{
  background-color: #5f27cd;
  color:#fff;
}

5. Customize the CSS class and ID of the context menu.

contextMenu({
  items: menuItems,
  className: "myClassName",
  id:"myId",
}).init(document.getElementById("myContainer"));

You Might Be Interested In:


Leave a Reply