How to change menu items dynamically in EJ2 JavaScript Context menu
4 Sep 20264 minutes to read
The items visible in the ContextMenu can be changed dynamically based on the target in which you open the ContextMenu. To achieve this behavior, initialize the ContextMenu with all items using the items property, and then based on the context in which you open the menu, hide or show the required items using the hideItems and showItems methods in the beforeOpen event.
In the following example, the data source for the Clipboard div (Cut, Copy, Paste) and the Editor div (Add, Edit, Delete) is changed on the beforeOpen event using the hideItems and showItems methods.
ej.base.enableRipple(true);
var menuItems = [
{
text: 'Cut'
},
{
text: 'Copy'
},
{
text: 'Paste'
},
{
text: 'Add'
},
{
text: 'Edit'
},
{
text: 'Delete'
}];
var menuOptions = {
target: '#target .e-div',
items: menuItems,
beforeOpen: beforeOpen
};
// Initialize ContextMenu component.
var menuObj = new ej.navigations.ContextMenu(menuOptions, '#contextmenu');
function beforeOpen (args) {
if (args.event.target.id === 'right') {
menuObj.hideItems(['Cut', 'Copy', 'Paste']);
menuObj.showItems(['Add', 'Edit', 'Delete']);
} else if (args.event.target.id === 'left') {
menuObj.showItems(['Cut', 'Copy', 'Paste']);
menuObj.hideItems(['Add','Edit','Delete']);
}
}<!DOCTYPE html><html lang="en"><head>
<title>Essential JS 2</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="description" content="Essential JS 2">
<meta name="author" content="Syncfusion">
<link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-base/styles/bootstrap5.3.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-buttons/styles/bootstrap5.3.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-lists/styles/bootstrap5.3.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-inputs/styles/bootstrap5.3.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-popups/styles/bootstrap5.3.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-navigations/styles/bootstrap5.3.css" rel="stylesheet">
<!--style reference from app-->
<link href="styles.css" rel="stylesheet">
<!--system js reference and configuration-->
<script src="https://cdn.syncfusion.com/ej2/34.2.2/dist/ej2.min.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<div id="target">
<div id="left" class="e-div">Clipboard</div>
<div id="right" class="e-div">Editor</div>
</div>
<!--element which is going to render-->
<ul id="contextmenu"></ul>
</div>
<script>
var ele = document.getElementById('container');
if(ele) {
ele.style.visibility = "visible";
}
</script>
<script src="index.js" type="text/javascript"></script>
</body></html>