Context Menu Clamps Into Viewport

Open a custom menu at the pointer, then clamp its box with Math.min and Math.max so it never spills past the viewport edges.

TypescriptData Integrity

Code

typescriptsnippet
30 lines
const menu = document.createElement('div');
menu.hidden = true;
menu.textContent = 'rename / duplicate / delete';
document.body.append(menu);

document.addEventListener('contextmenu', (event) => {
  event.preventDefault(); // suppress the native menu
  menu.hidden = false;
  // clamp the box back inside the viewport with Math.min/Math.max
  const box = menu.getBoundingClientRect();
  const x = Math.min(event.clientX, window.innerWidth - box.width);
  const y = Math.min(event.clientY, window.innerHeight - box.height);
  menu.style.left = Math.max(0, x) + 'px';
  menu.style.top = Math.max(0, y) + 'px';
  console.log('menu placed at', Math.max(0, x), Math.max(0, y), 'for pointer', event.clientX, event.clientY);
});

document.addEventListener('pointerdown', () => {
  menu.hidden = true;
});

// pointer near the bottom-right corner: the clamp pulls the menu back
document.dispatchEvent(new MouseEvent('contextmenu', {
  bubbles: true,
  clientX: window.innerWidth - 5,
  clientY: window.innerHeight - 5,
}));

document.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
console.log('menu dismissed:', menu.hidden);

How the demo unfolds

The file’s state is a handful of top-level bindings: menu.

What to watch for

  • The snippet leans on document, window — browser-only surfaces a bare Node process cannot provide.

Applying it

The run prints menu placed at, menu dismissed: — each prefix names the step that produced it.

Statements that matter

document.addEventListener('pointerdown', () => {
  menu.hidden = true;
});

Interactive Tools for This Topic

FAQ

Does Context Menu Clamps Into Viewport run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.