I have a class called ContextMenu and it is made to replace the default contextmenu that the browser shows whenever you right click on the page.
This menu needs some eventListeners applied to it's children.
<div id="contextmenu" class="hidden">
<ul>
<li id="download-file" class="action">Download</li>
<li id="rename-file" class="action">Rename</li>
<li id="delete-file" class="action">Delete</li>
<li id="details-file" class="action">Details</li>
</ul>
</div>
this is the html for the contextmenu
export default class ContextMenu
{
contextMenu
events
actions
selectedItem
constructor(HTMLContextMenu)
{
this.contextMenu = HTMLContextMenu
window.document.onmousedown = (event) => this.show(event)
this.events = ['click', 'touchstart']
this.actions = window.document.querySelectorAll('.action') // all elements that have to trigger an eventListener have the class "action"
for (const event in this.events)
{
this.actions[0].addEventListener(event, this.download, false)
this.actions[1].addEventListener(event, this.rename, false)
this.actions[2].addEventListener(event, this.delete, false)
this.actions[3].addEventListener(event, this.details, false)
}
this.selectedItem = null
}
this is the javascript, i did not paste the entire class, just what's relevant for the problem. As you can see the for in loop takes care of the eventListeners applying 8 listeners in total. The problem is that whenever i click the element nothing happens
I have found the issue. The for (const event in this.events) loop is wrong, it has to be for (const event of this.events) in order to make it work.
for (const event of this.events)
{
this.actions[0].addEventListener(event, this.download, false)
}
As iQucik said you are using the wrong keyword in your loop. In case you're using iterable objects you have to use of keyword otherwise use in keyword for enumerable objects.
Some references:
MDN Docs for-of loop: MDN Docs for..of
MDN Docs for-in loop: MDN Docs for..in
export default class ContextMenu
{
contextMenu
events
actions
selectedItem
constructor(HTMLContextMenu)
{
this.contextMenu = HTMLContextMenu
window.document.onmousedown = (event) => this.show(event)
this.events = ['click', 'touchstart']
this.actions = window.document.querySelectorAll('.action') // all elements that have to trigger an eventListener have the class "action"
for (const event of this.events)
{
this.actions[0].addEventListener(event, this.download, false)
this.actions[1].addEventListener(event, this.rename, false)
this.actions[2].addEventListener(event, this.delete, false)
this.actions[3].addEventListener(event, this.details, false)
}
this.selectedItem = null
}
<div id="contextmenu" class="hidden">
<ul>
<li id="download-file" class="action">Download</li>
<li id="rename-file" class="action">Rename</li>
<li id="delete-file" class="action">Delete</li>
<li id="details-file" class="action">Details</li>
</ul>
</div>