Browser and contexmenu intersecting halfway

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

Answer №1

Here is the solution that worked like a charm:

function showContextMenuFunction(e){
    e.preventDefault();
    displayContextMenu();
    if(e.clientY + contextMenu.offsetHeight < window.innerHeight) {
        contextMenu.style.top = e.clientY + "px";
    }
    else {
        contextMenu.style.top = (window.innerHeight - contextMenu.offsetHeight) + "px";
    }
    if(e.clientX + contextMenu.offsetWidth < window.innerWidth) {
        contextMenu.style.left = e.clientX + "px";
    }
    else {
        contextMenu.style.left = (window.innerWidth - contextMenu.offsetWidth) + "px";
    }
}
window.addEventListener("contextmenu", showContextMenuFunction);
window.addEventListener("click", function(){
    displayContextMenu(false);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a tab resizing effect similar to Chrome using only CSS

I am attempting to design tabs that can dynamically resize similar to how Chrome tabs behave. However, I am uncertain if achieving this functionality is possible without relying on JavaScript. Browser compatibility is not a concern for me; my main goal is ...

Ways to stop button from wrapping inside a div

While working on a search page, I encountered an issue where the submit button overlaps with the text input when zooming in due to lack of space. Is there a solution to prevent this overlapping and keep the layout intact? HTML <input type="text> &l ...

Is there a glitch with child margins in a relative-absolute positioning setup?

Could someone shed some light on how I can prevent the margin from one sibling div affecting another? The browser's layout seems a bit baffling to me in this scenario. I'm attempting to position the yellow box relative to its parent, but the pre ...

Load texture programmatically instead of using MTL files

I've successfully loaded an OBJ file and linked it with an MTL to provide a texture. However, I'm struggling to specify which texture should be associated with the model directly in the code; it seems that the texture only appears on the model if ...

Working with numerous query parameters within AngularJS

When interfacing with an external service, I’m receiving query parameters in the following format: url/?error=someError&error_description=someErrorDescription In my app.js file, I have attempted to handle this using the routeProvider as shown below ...

Angular: Identifier for Dropdown with Multiple Selection

I have recently set up a multi select dropdown with checkboxes by following the instructions provided in this post: https://github.com/NileshPatel17/ng-multiselect-dropdown This is how I implemented it: <div (mouseleave)="showDropDown = false" [class. ...

Why won't divs align vertically in the center?

I'm struggling to create a navigation bar layout where the icons are centered both horizontally and vertically within their cells. http://jsfiddle.net/digorydoo/j2v5m7gr/ I can't seem to pinpoint what's causing the issue with my current la ...

Making sure that a commitment does not come to fruition

Perhaps this code snippet below functions correctly as it is, but I'm uncertain if it's the best approach to prevent potential runtime issues. Here's the code in question: const ep = `${environment.api.baseUrl}/login`; return this.http.pos ...

loop through the array of objects using ng-repeat in Angular

I am facing an issue where I need to display the data fetched from a service in my application. The service response is as follows: Object {resultado:array[2], mensaje: "4 personas `necesita tu ayuda"} Currently, the "resultado" field contains an object ...

First experience with Django Bootstrap Modal Ajax was flawless, but on the second attempt, it was not as successful

I am currently utilizing Django 2.2 in conjunction with Bootstrap. The method implemented is as follows: Triggering the opening of a modal window, User updates the data, User saves the data, Underlying table from where the window originated is updated a ...

WebView on Android still showing highlighted text even after selection has been cleared

When using my web app on an android WebView, I've noticed that whenever I click on something or navigate somewhere, a blue highlight appears on the container div. It sometimes disappears quickly, but other times it remains until clicking elsewhere. I ...

Enable the set body to have certain sections that are scrollable by setting overflow=hidden

I am currently working on a website that features the following structure: <body> <section></section> <section></section> ... </body> To prevent scroll bars on the body, I have set the CSS property body{overflow:hidden ...

Delete all pictures beginning with this specific ID from the posts

Currently, I have approximately 300 Wordpress posts, and each one contains a "tracking pixel" from a previously used service (which is implemented using IMG tags). This is an example of how it appears: <img id="serviceTrack_3274570" style="margin: 0px ...

What are the steps to limit the usage of angular.module('myApp', ['ngGrid', 'ui.bootstrap', 'kendo.directives'])?

I have two JavaScript files with AngularJS code. The first file, myjs1.js, includes the module: angular.module('myApp', [ 'ngGrid', 'ui.bootstrap', 'kendo.directives' ]); The second file, myjs2.js, also includes th ...

Using Higher Order Components in React with TypeScript to pass a component as a prop

Exploring the steps outlined in this guide: https://reacttraining.com/react-router/web/example/auth-workflow. Attempting to replicate the code: const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props = ...

What is the process for adding a Contact Us page to a website?

I recently created a website using html, css and Javascript. I would like to include a 'get in touch' page where visitors can send me messages directly on the site. What steps should I take to make this happen? Is it necessary to set up a databas ...

Is there a way to update the background dynamically?

I'm currently developing a weather application and I want the background to change dynamically based on the data retrieved from an API. Initially, I set up a variable and utilized an if statement for this purpose. However, I encountered difficulty in ...

Interactive back button for seamless navigation back to the originating modal

This website is built on Bootstrap 4. As I develop this site, there are a total of 17 different modals. Specific words in each modal are linked to other modals for additional information. However, getting back to the previous modal requires closing the ...

Using JavaScript and the PapaParse library, you can easily convert CSV data into an array

My current task involves using Papaparse to convert a csv file into a json object. The API requires the data to be structured like this: "data": [ { "id": 1, "nombre": "AGUASBLANCAS-AGB&qu ...

Exploring the Unchanging Object3D Characteristics of ThreeJS Version 68

According to the transition notes from r67 to r68, it is stated that: Object3D's position, rotation, quaternion and scale properties are now immutable. How does this impact practical implementation? I am seeking further clarification on this matte ...