Change menu items dynamically in EJ2 JavaScript Context menu control

2 May 20234 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 ContextMenu with all items using items property and then based on the context you open hide/show required items using hideItems/showItems method in beforeOpen event.

In the following example, the datasource for Clipboard div is Cut, Copy, Paste and for the Editor div is Add, Edit, Delete is changed on beforeOpen event using hideItems and showItems method.


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 ( === 'right') {
        menuObj.hideItems(['Cut', 'Copy', 'Paste']);
        menuObj.showItems(['Add', 'Edit', 'Delete']);
    } else if ( === 'left') {
        menuObj.showItems(['Cut', 'Copy', 'Paste']);
<!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="" rel="stylesheet">
    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">

    <!--style reference from app-->
    <link href="styles.css" rel="stylesheet">

    <!--system js reference and configuration-->
<script src="" type="text/javascript"></script>
<script src="" type ="text/javascript"></script>

    <div id="container">
        <div id="target">
            <div id="left" class="e-div">Clipboard</div>
            <div id="right" class="e-div">Editor</div>
        <!--element which is going to render-->
        <ul id="contextmenu"></ul>

var ele = document.getElementById('container');
if(ele) { = "visible";
<script src="index.js" type="text/javascript"></script>