I am facing an issue with the positioning of my context menu. When I right-click and scroll down, the menu does not maintain its regular position. Instead of appearing to the right of the mouse cursor when stationary, it moves below the cursor based on how far I scroll. I have attempted using clientY
and scrollY
, but these fixes did not resolve the problem. Here is a code snippet showcasing the implementation:
// JavaScript function to display the custom context menu with a sliding effect
function showContextMenu(x, y) {
var menu = document.querySelector(".ctx-context-menu");
if (menu.classList.contains("ctx-menu-visible")) {
menu.classList.add("ctx-menu-slide");
menu.style.left = x + "px";
menu.style.top = y + "px";
setTimeout(function () {
menu.classList.remove("ctx-menu-slide");
}, 500);
} else {
menu.style.left = x + "px";
menu.style.top = y + "px";
menu.classList.add("ctx-menu-visible");
}
}
// Function to hide the custom context menu
function hideContextMenu() {
var menu = document.querySelector(".ctx-context-menu");
menu.classList.remove("ctx-menu-visible");
}
document.addEventListener("contextmenu", function (e) {
var menu = document.getElementById("ctxContextMenu");
if (menu.contains(e.target)) {
return;
}
e.preventDefault();
showContextMenu(e.pageX, e.pageY);
});
document.addEventListener("click", function (e) {
var menu = document.getElementById("ctxContextMenu");
if (!menu.contains(e.target)) {
hideContextMenu();
}
});
document.getElementById("ctxContextMenu").addEventListener("contextmenu", function (e) {
e.preventDefault();
});
document.addEventListener("keydown", function (e) {
if (e.key === "Escape") {
hideContextMenu();
}
});
/* Context Menu Styles */
.ctx-context-menu {
opacity: 0;
position: fixed;
z-index: 10000;
width: 150px;
background-color: #1a1a1a;
border: 2px solid #ff0000;
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
border-radius: 10px;
padding: 10px 0;
transition: opacity 0.15s linear;
pointer-events: none;
}
.ctx-menu-slide {
transition: left 0.25s, top 0.25s;
}
.ctx-menu-visible {
opacity: 1;
pointer-events: auto;
}
.ctx-context-menu-item {
color: #808080;
cursor: pointer;
text-decoration: none;
transition: color 0.15s linear;
}
.ctx-context-menu-item:hover {
color: #ff00ff;
}
<nav id="ctxContextMenu" class="ctx-context-menu">
<ul class="navbar-nav text-center gap-2">
<li>
<a class="ctx-context-menu-item text-center mx-2">First Action</a>
</li>
<hr class="m-0 mx-2" />
<li>
<a class="ctx-context-menu-item text-center mx-2">Second Action</a>
</li>
<hr class="m-0 mx-2" />
<li>
<a class="ctx-context-menu-item text-center mx-2">Third Action</a>
</li>
</ul>
</nav>
I am working on creating a custom context menu as a replacement for the browser's default context menu.
To truly experience the issue, I recommend expanding the code snippet to fullscreen mode. Scroll down slightly and observe that the context menu appears below the cursor.