I have successfully implemented a custom context menu in my HTML project. It functions well, but I am facing an issue where half of the menu appears off-screen to the right. Is there a way to detect this and reposition the menu above the mouse pointer?
Here are some images demonstrating the current setup: Image 1 Image 2
This is the code I am currently using:
Javascript:
const cm = document.querySelector(".custom-cm");
function showContextMenu(show = true) {
cm.style.display = show ? "block" : "none";
}
window.addEventListener("contextmenu", e => {
e.preventDefault();
showContextMenu();
cm.style.top = e.y + "px" + (cm.offsetHeight > window.innerHeight) ? window.innerHeight - cm.offsetHeight : e.y + "px";
cm.style.left = e.x + "px" + (cm.offsetWidth > window.innerWidth) ? window.innerWidth - cm.offsetWidth : e.x + "px";
});
window.addEventListener("click", () => {
showContextMenu(false);
});
HTML:
<div class="custom-cm">
<div class="custom-cm__item" onclick="closeAndFocus()">Enter Text</div>
<div class="custom-cm__item" onclick="copyText()">Copy Text</div>
<div class="custom-cm__divider"></div>
<div class="custom-cm__item" onclick="helpMenu()">Help</div>
<div id="SavePicLine" class="custom-cm__divider" style="display: none;"></div>
<div id="SavePic" class="custom-cm__item" onclick="downloadPic()" style="display: none;">Save Image</div>
<div class="custom-cm__divider"></div>
<div class="custom-cm__item" onclick="window.location.reload()">Refresh</div>
<div class="custom-cm__item" onclick="showContextMenu(false);">Close</div>
</div>
CSS:
.custom-cm {
background-color: #ffffff;
border: 1px solid #cccccc;
box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.2);
padding: 10px 0;
position: absolute;
top: 0;
left: 0;
width: 150px;
display: none;
}
.custom-cm__item {
cursor: pointer;
padding: 8px 15px;
}
.custom-cm__item:hover {
background-color: #f3f3f3;
}
.custom-cm__divider {
border-bottom: 1px solid #eeeeee;
margin: 10px 0;
}
You can test it out here: CodePen Link