We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to add Context Menu to List view?

I have a ListView (using local JSON array data) and I would like to add a Context Menu to the items so that a user can take an action on the selected item..  How is this best accomplished?  The listview item is not selected when the context menu is displayed with right-click.  How can I determine the correct listview item from within the menu item's "select" event?


myList = new ej.lists.ListView({
dataSource: [{id:1, name:"Item 1"},{id:2, name:"Item 2"},{id:3, name:"Item 3"}],
fields: { text: 'name', value: 'id' },
showHeader: false,
});
myList.appendTo('#listview');

var menuItems = [{text: 'Download'}, {text: 'Delete'}];
var menuOptions = {target: '#listview', items: menuItems, select: function(args) {} };
var menuObj = new ej.navigations.ContextMenu(menuOptions, '#contextmenu');


1 Reply

LD LeoLavanya Dhanaraj Syncfusion Team March 30, 2023 12:02 PM UTC

Hi John,


Greetings from Syncfusion support.


Based on the details you have shared, we understand that you want to add a context menu based on the selected list items in the Syncfusion ListView component. Currently, we do not have a click event for the EJ2 ListView component; we only have the select event, which does not capture the right-click action.


However, we have fulfilled your requirement by using the contextmenu event inside the list items addEventListener. Here, we retrieved the selected list item details and added the context menu based on it. For your reference, we have included a sample and code snippets with the latest version.


Sample : https://stackblitz.com/edit/qlrpt8-pnzdbj?file=index.js,index.html


[index.html]

<div id="listview" tabindex="1">

    <ul>

      <li>Hennessey Venom</li> …

      <li>Lamborghini Veneno</li>

    </ul>

</div>

<ul id="contextMenu"></ul>

 

[index.js]

//Initialize ListView component

var listObj = new ej.lists.ListView();

listObj.appendTo('#listview');

 

//Render the context menu with target as ListView

var menuItems = [{ text: ' Item 1' }, { text: ' Item 2' }, { text: ' Item 3' }];

var menuOptions = {

  target: '#listview',

  items: menuItems,

};

var menuObj = new ej.navigations.ContextMenu(menuOptions, '#contextMenu');

 

const items = document.getElementsByClassName('e-list-item');

let clickedItem = '';

Array.from(items).forEach(function (item) {

  item.addEventListener('contextmenu', function (clicnEvent) {

    window.clickedItem = clicnEvent.currentTarget.getAttribute('data-uid');

  });

});


Check out the shared sample at your end and let us know if the provided sample is suitable for your requirement. Please get back to us if you need any further assistance.


Regards,

Leo Lavanya Dhanaraj


Loader.
Live Chat Icon For mobile
Up arrow icon