I'm trying to add a context menu on a ListView in WinJS (Windows Phone 8.1 UWP). First I wanted to add it by selecting the elements and adding an EventListenter. This is my HTML Code:
<div class="friendsTemplate" data-win-control="WinJS.Binding.Template">
<div class="templatecontainer">
<img src="/images/default-avatar.png" />
<div class="itemcontainer">
<div class="itemtitle label-extralarge" data-win-bind="textContent: nickname"></div>
<div class="label-mediummid" data-win-bind="textContent: quotation"></div>
</div>
</div>
</div>
<div id="listView" data-win-control="WinJS.UI.ListView"
data-win-options="{
itemDataSource: WinJS.Application.sessionState.friendslist.dataSource,
itemTemplate: select('.friendsTemplate'),
layout: { type: WinJS.UI.ListLayout }
}"></div>
This is my first approach which failed:
var myList = document.querySelectorAll('.templatecontainer');
for(var i = 0; i < myList.length; i++) {
myList[i].addEventListener('contextmenu', function(e) {
// code for context menu
}
}
But myList is empty. Then I tried a different approach:
var myList = document.getElementById('listView');
myList.addEventListener('contextmenu', function (e) {
console.log(e.srcElement.getElementsByClassName('templatecontainer'));
});
I manually inspected e in the function. The data is there! The elements with the class names are there!
I have no idea what's going on. How can I create a context menu in JavaScript in my listView per item?
I finally found a solution after hours. That way I can get the index of the item in the list and it's nickname. Those are sufficient for my cases. Thanks!
document.getElementById('listView').winControl.addEventListener('contextmenu', function () {
var index = document.getElementById('listView').winControl.currentItem.index;
var selectedItem = document.getElementById('listView').winControl.elementFromIndex(index);
var nickname = selectedItem.getElementsByClassName('nickname')[0].innerText;
})