October 22, 2024
Chicago 12, Melborne City, USA
HTML

How to make a hardcoded right-click menu to appear on the screen?


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>



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video