On my own compiler, the menu doesn’t even change a bit. When I tested here, it’s a bit better, for it does block the original default right-click menu. However, this hardcoded JS one does not appear either. I’d like to ask is there any problem with the code here, or it just doesn’t work like that?
const rMenu = document.getElementById('rClickMenu');
var timeout;
var lastTap = 0;
document.addEventListener("contextmenu", (e) => {
e.preventDefault();
let mouseX = e.clientX || e.touches[0].clientX;
let mouseY = e.clientY || e.touches[0].clientY;
let menuHeight = rMenu.getBoundingClientRect().height;
let menuWidth = rMenu.getBoundingClientRect().width;
let width = window.innerWidth;
let height = window.innerHeight;
if (width - mouseX <= 200) {
rMenu.setAttribute("border-radius", "5px 0 5px 5px");
rMenu.setAttribute("left", (width - menuWidth) + "px");
rMenu.setAttribute("top", mouseY + "px");
if (height - mouseY <= 200) {
rMenu.setAttribute("top", (mouseY - menuHeight) + "px");
rMenu.setAttribute("border-radius", "5px 5px 0 5px");
}
} else {
rMenu.setAttribute("border-radius", "0 5px 5px 5px");
rMenu.setAttribute("left", mouseX + "px");
rMenu.setAttribute("top", mouseY + "px");
if (height - mouseY <= 200) {
rMenu.setAttribute("top", (mouseY - menuHeight) + "px");
rMenu.setAttribute("border-radius", "5px 5px 5px 0");
}
}
rMenu.setAttribute("visibility", "visible");
},
{ passive: false }
);
document.addEventListener("click", function (e) {
if (!rMenu.contains(e.target)) {
rMenu.setAttribute("visibility", "hidden");
}
});
section #rClickMenu {
background-color: #ffffff;
box-shadow: 0 0 20px rgba(37, 40, 42, 0.22);
color: #000000;
width: 10em;
padding: 0.8em 0.6em;
font-size: 1.3rem;
position: fixed;
visibility: hidden;
}
section #rClickMenu div {
padding: 0.3em 1.2em;
}
section #rClickMenu div:hover {
cursor: pointer;
}
<section>
<div id="rClickMenu">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</section>
2
Answers
You should be setting the
style
attribute.I put together this Javascript to be a generic solution for creating a context menu. You can create your menu from an array (see
sample
) and use applyClickFunction to add a click function to all items.After you’ve called
createMenu
you need to set css propertiesdisplay
(normally ‘block’) andposition
(normally "absolute" or "fixed") because this is set up to work withabsolute
andfixed
scenarios and then add it to the parent component.