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

Using the fetch method to consume a RapidAPI JSON response

Currently, I am in the process of learning React Native and have initiated a project for that purpose. In this project, I have integrated RapidAPI (link: ) to fetch necessary data. Upon hitting the API, I receive a 200OK status, but unfortunately, I am fa ...

Transform form data into a specialized JSON structure

I have a form set up in the following way: <form id="myForm" ng-submit="submitForm()"> <select name="ItemName" ng-controller="ItemController"> <option value="" selected disabled>Select</option> <option ng-rep ...

Node.js program closes immediately upon Java startup

I am building a Discord bot that features a Java FXML interface and utilizes a Node.js program to function as an Audio playing bot. However, I am encountering an issue where the process for Node.js closes immediately when opened in Java. The problem arise ...

What is the correlation between using em font sizes and disrupting line-height?

I initially set my body element's font-size to 19px, and then started using em units for various elements. Unfortunately, I am experiencing irregularities with line-heights. For example, when I use a font-size of 0.6em, the line height becomes uneven ...

Can the max-height CSS media-query be utilized safely?

It seems that using the max-height media query is proving to be quite a challenge due to an issue with Chrome 67 on iOS. The problem arises when users scroll on Chrome as it constantly adds and removes the address bar. This action causes the max-height va ...

Unit tests manipulating JavaScript functions to return undefined values

Currently, I am in the process of testing some JavaScript functions within a larger React application. These functions heavily utilize the module pattern, which leads me to believe that my misunderstanding lies within this pattern. The script I am testing ...

Can we stub these types of functions in any manner?

One file named helperFunction.js contains the following code: module.exports = (arg1, arg2) => { \\function body } To use this function in another file named file.js, you can simply call it like this: let helperFunction = require(' ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

Tips for retrieving next-auth authOptions from an asynchronous function

I need to retrieve values from AWS Secrets Manager and integrate them into the authOptions configuration for next-auth. The code implementation I have is as follows: export const buildAuthOptions = async () => { const secrets: AuthSecrets = await getS ...

Interactive sidebar component with navigation and animated section markers

For weeks, I've been attempting to create a navigation sidebar similar to the ones shown in these images: Even though getbootstrap.com/components offers appealing navigation sidebars, I have not found a built-in component in their library. This has m ...

Include the url of the html file in your JavaScript code

I have a piece of code that I want to include in my JavaScript instead of HTML. The code is as follows: <script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script> Since all my functions are written in JavaScript, I ...

Retrieve all entries and merge a field with aggregated information in Mongoose (MongoDB)

I am faced with the challenge of working with two Mongo collections, Users and Activities. The Activities collection consists of fields such as createdAt (type Date), hoursWorked (type Number), and a reference to the user through the user field. On the oth ...

Displaying content on a webpage using PHP, AJAX, and HTML

Looking to update my current form setup. I have a basic Form below: <form action="" method="POST"> <input type="button" value="Generate Numbers" onclick="on_callPhp1()"/> </form> Accompanied by this javascript code: <script type="te ...

Ways to terminate all AJAX requests within a for loop

Is there a way to cancel all AJAX requests that are being handled by a for loop? var url = ["www.example.com","www.example2.com",....]; for (var i = 0; i < url.length; i++) { var XHR = $.get(url[i], function(data) { //do something }); } I attemp ...

The XHR Get request fails to load the HTML content sent from the Express application

As I embark on building my inaugural express app, I have encountered a shift in sending requests from the front-end. Previously, all requests were initiated by anchor elements for GET requests and form elements for POST requests, with server responses hand ...

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

An issue occurred while attempting to execute a function in AngularJS

Currently, I am in the process of developing a cross-platform application using AngularJS, Monaca, and Onsen UI. My current challenge involves calling a function in my controller from an ng-click() event on my view. However, upon clicking the button that ...

The situation arose where Next.js could not access the cookie due to

Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions. In this component, I am trying to fetch user data from my ...

Can you specify the third argument sent to the listener?

Recently I delved into exploring the capabilities of the d3 framework. One thing that caught my attention was the presence of a third parameter in the event listener for v3. Despite always being 0, I couldn't find any explanation on its intended purpo ...

How can I line up two divs horizontally within a container div?

Apologies if my terminology is off, I am relatively new to this. My goal is to align two divs horizontally, one containing an image and the other the message content. I have created a messaging user interface. Everything was functioning correctly until I ...