I want to add onclick events for dynamically created popup menu on site. Here is a code:
<div id="rmenu">
<div class="rmenu_options">
<a href="#" id="start" >Create starting point</a>
</div>
<div class="rmenu_options">
<a href="#" id="goal">Create goal point</a>
</div>
</div>
.rmenu_options {
margin-bottom: 7px;
cursor: pointer;
}
#rmenu {
display: none;
position: absolute;
background: bisque;
width: 175px;
height: 55px;
padding: 10px;
border-radius: 6px;
font-size: 18px;
}
// create mouse rightclick menu
function mouseX(evt) {
if (evt.pageX) {
return evt.pageX;
} else if (evt.clientX) {
return evt.clientX + (document.documentElement.scrollLeft ?
document.documentElement.scrollLeft :
document.body.scrollLeft);
} else {
return null;
}
}
function mouseY(evt) {
if (evt.pageY) {
return evt.pageY;
} else if (evt.clientY) {
return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
} else {
return null;
}
}
window.oncontextmenu = function openRightClickMenu (e) {
e.preventDefault();
document.getElementById("rmenu").style.display = "block";
document.getElementById("rmenu").style.top = mouseY(e) + 'px';
document.getElementById("rmenu").style.left = mouseX(e) + 'px';
document.getElementById("rmenu").classList.add("opened");
window.event.returnValue = false;
}
// remove mouse rightclick menu
document.onmousedown = function removeRightClickMenu (e) {
if (e.which == 1) {
if (document.getElementById("rmenu").classList == "opened") {
document.getElementById("rmenu").classList.remove("opened");
document.getElementById("rmenu").style.display = "none";
}
}
}
// ???
document.getElementById('rmenu').addEventListener("click", function() {
function whatToDo (e) {
if (e.target.id == 'start') {
console.log("start clicked")
} else if (e.target.id == 'goal') {
console.log("goal clicked")
}
}
});
How to add onclick event for dynamically created popup menu?
I was surfing the internet and then created addEventListener like this author recommends, but nothing changed. What I've done wrong?
I marked my problem function with comment (???)