Prevent the context menu from being truncated on the right side of the page

When I right-click in the right portion of my page, my context menu gets cut off. The issue is illustrated here: https://i.sstatic.net/FZguG.jpg

I have tried looking for solutions on other StackOverflow pages and trying different demos, but all suggestions address the same problem as mentioned above. Leaving comments on related posts did not yield any helpful responses either.

Update

Code:

In an attempt to resolve this issue, I am using the following code snippet:

var menu = document.querySelector('.menu');

function showMenu(x, y) {
  menu.style.left = x + 'px';
  menu.style.top = y + 'px';
  menu.classList.add('menu-show');
}

function hideMenu() {
  menu.classList.remove('menu-show');
}

function onContextMenu(e) {
  e.preventDefault();
  showMenu(e.pageX, e.pageY);
  document.addEventListener('mousedown', onMouseDown, false);
}

function onMouseDown(e) {
  hideMenu();
  document.removeEventListener('mousedown', onMouseDown);
}

document.addEventListener('contextmenu', onContextMenu, false);
A snippet of CSS related to the menu:

/* Page */

html {
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, #fff 0%, #a6b9c1 100%) no-repeat;
}
...
<ul class="menu">
  ...
</ul>

<div class="container">
  <h1>Context Menu</h1>
  <h2>(right-click anywhere)</h2>
</div>

Answer №1

You can achieve this functionality by implementing a simple comparison. Instead of directly setting the position of the context menu (

menu.style.left = e.pageX + "px";
), you can check if it will fit within the viewport:

  var contextMenuWidth = 250;
  var contextSubMenuWidth = 250;
  var leftPos = ''
  if (e.pageX < window.innerWidth - contextMenuWidth) {
    leftPos = `${e.pageX}px`;
  } else {
    leftPos = `${e.pageX - contextMenuWidth}px`;
  }
  if (e.pageX < window.innerWidth - contextMenuWidth - contextSubMenuWidth) {
    menu.classList.remove("sub-left");
  } else {
    menu.classList.add("sub-left");
  }
  menu.style.left = leftPos;

This logic verifies if the cursor position (e.pageX) is within the distance of the context menus' width (contextMenuWidth) from the right side of the screen (window.innerWidth). If so, adjust the left position accordingly.

The if statement also adds or removes a class to modify the sub-menu's position based on the context menu's location.

.sub-left .menu-sub-list { 
  left: -100%;
  right: 0;
}

In addition, template literals are used for creating CSS strings like `${numberVariable}px`, which is more efficient than concatenating strings with the + operator.

For better organization and flexibility, consider storing the context menu width as a variable rather than hard coding it in the script:

...

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

Show a pre-made HTML element using the jQuery validation plugin

I am trying to use the jQuery validation plugin to display symbols. When I enter a value incorrectly, the validation error is shown (which is fine) and it should display my custom symbol .validation-incorrect. Once the validation passes, I want to show t ...

Creating a jQuery-powered dynamic select field in Rails 3

After implementing the dynamic select functionality from this example on GitHub (GitHub Link), I successfully integrated dynamic selection for car models in my form for adding a new car. The form now filters car models based on the selected car name, and i ...

opacity of highcharts heatmap data points reduces to zero

Recently, I integrated a Heat Map feature from the Highcharts library into my app. However, I encountered a strange issue where certain rows of data were not displaying on the map. Please refer to the screenshot below for reference: Upon inspecting the el ...

Issue with hidden event callback not functioning properly in Bootstrap 3 popover

After studying this example, I attempted to incorporate a hidden callback function. While the show callback is functioning perfectly, the hidden callback seems to be ineffective. Can someone shed light on why this issue is occurring? To showcase the probl ...

What is the best approach for creating unit test cases for recursive functions in node.js using the Mocha testing framework?

( async ()=>{ // code })(); This particular self-invoking function is located within a JavaScript file that has not been exported. I am looking to import it in order to write unit tests, but I have yet to find a solution. I attempted to use the rewi ...

Creating a personalized gradient using Tailwind CSS and Daisy UI framework

I’m attempting to incorporate a unique gradient into my next.js application with the help of Tailwind CSS and Daisy UI. Below is the specific code snippet I plan on using: background: linear-gradient(180deg, rgba(192, 192, 192, 0.04) 0%, rgba(201, 180, ...

Using AngularJS to maintain a 'Token' throughout the duration of the application

Currently utilizing AngularJS with Restangular to authenticate a user during the login process. Once authenticated, a 'Token' is returned which must be utilized for all subsequent requests. My inquiry pertains to the optimal method of storing th ...

What is the reason behind document.getElementById returning null?

I am currently working on dynamically creating a submit form. However, when I click the submit button, I encounter an error on the following line. var name = document.getElementById("form").value; Here is the complete code snippet for reference. Script ...

JavaScript's Scoped Exports concept

After exporting something in JavaScript, let's consider a scenario where we have a file named 'foo.js' with the line: export default foo; This allows us to import it globally from any other file. But what if there is a need to restrict thi ...

Looking for a jquery plugin that allows you to easily toggle between showing and hiding elements

I'm in need of some guidance on finding a slide window plugin in jQuery. My goal is to create a feature similar to Yahoo Mail, where users can hide the advertisement pane shown on the right side by clicking a button. I would greatly appreciate any as ...

Link causing chaos in CSS animation

I've created a CSS animated banner. You can view the result here. However, I'm facing an issue where adding a hyperlink to some of the pictures is causing the animation to mess up. The first picture has a href attribute, making it smaller and not ...

What is the best way to add values to the nested keys within an object in the model using FormData?

My server-side modal includes an object structure as follows: location: { lat: { type: Number }, lng: { type: Number } }, I now need to update the values within the lat and lng properties inside the location object. How can ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Filter Angular.js by precise values (exact match)

Check out this HTML code snippet: <ul ng-repeat="friend in friends | filter: { age: '2' } | orderBy: 'name' "> <li>{{friend.name}}</li> </ul> Here is the $scope variable being used: $scope.friends = [ ...

Display the website logo when users share on WhatsApp

My goal is to have my website icon appear in WhatsApp when I share it (similar to the example below). https://i.stack.imgur.com/KCWi8.jpg I initially tried using this code, but it didn't work: <link rel="shortcut icon" href="css/img/favicon/favi ...

Struggling with tictactoe using php/ajax is becoming quite a challenge

Being a first-year student, I am new to this. Our course project involves creating a tictactoe game using Ajax and PHP for SQL interaction. We started with a client-side tictactoe example in JavaScript, but now we are stuck at the final piece of code. Esse ...

Building a personalized payment experience using Python Flask and Stripe Checkout

I'm attempting to set up a customized checkout integration with Stripe on my Flask web application and I've encountered some issues. After copying the code from the Stripe documentation (located at https://stripe.com/docs/checkout#integration-cu ...

How CSS properties can cause one div to push down another

I am looking to incorporate a simple sidebar into an existing layout (content). Here is what I have so far: HTML <div class="container"> <div class="side-menui"> </div> .... </div> Full HTML <div class="c ...

What could be causing the lack of space between the elements of form-inline?

Check out the demo here: http://jsfiddle.net/sunnycpp/MPACc/4/ Here is the same code pasted below: HTML <div class="container"> <debug-bar ng-controller="parentController"> <debug-bar ng-controller="childController"> <deb ...

Adjust the max-height to occupy the entire available space

One of the challenges I'm facing with my web application is designing the layout in a way that all elements interact seamlessly. The structure is as follows: <body> <nav> <-- top navigation bar <ol> <-- breadc ...