How to Position a Context Menu Opened from the Keyboard

A table of orders on a purple gradient with one row focused and a context menu opened at the centre of that row, next to a Shift and F10 key pair

A custom context menu opened with the mouse has an easy job: the contextmenu event carries the pointer’s position, and the menu opens there. The same menu opened from the keyboard, with Shift+F10 or the Menu key, has no pointer to follow. Something still has to decide where it appears, and the obvious answers put it in the wrong place as soon as the page scrolls.

This guide shows which keyboard gestures reach your code at all, how to pick the point when they do not bring one, and how to build a small context menu in plain JavaScript that opens next to the focused element whether that element is fully visible, half scrolled out of its container, or not on the screen at all.

Table of Contents

Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


What the browser gives you

Before writing any code I measured what arrives in a page that listens for keydown and contextmenu while a focusable element has the focus. Everything in this table was run on a Mac, and the keys were sent by browser automation, not pressed on a keyboard: a Mac keyboard has no Menu key, and Shift+F10 is not a convention there. The table shows what each browser does with the key once it receives it, and nothing about what an operating system does before that.

gesture Chromium Firefox
right-click contextmenu at the pointer, button 2 contextmenu at the pointer, button 2
Menu key (ContextMenu) keydown, then contextmenu at the centre of the focused element, button -1 keydown only
Shift+F10 keydown only keydown only
Menu key with preventDefault() on keydown no contextmenu not applicable

Three more things came out of the same runs.

A screen reader sends a point too. VoiceOver has its own command for opening the context menu of the item under its cursor. With the focus on a table row, that command produced a contextmenu event in Safari, Chromium and Firefox, and in all three the point was the centre of the row’s first cell. button was -1 in Chromium and 2 in the other two. No event in these runs had both coordinates equal to zero. With the VoiceOver cursor on a plain paragraph that cannot hold the focus, Firefox sent the event at the centre of the window.

Chromium picks the centre of what is inside the window. When the focused element reached past the top of the window, the event’s point was the centre of the part inside the window, not the centre of the whole element. Chromium also scrolled a focused element that was out of view back into view before it sent the event. The point was not clipped by a scrolling container around the element: a 500 px element inside a 200 px scroller got its point at its own centre, which was the bottom edge of the scroller.

That matches the source. I read ShowNonLocatedContextMenu in Chromium’s third_party/blink/renderer/core/input/event_handler.cc (commit c13d45ed96): with a text selection the menu opens at the selection, with a focused element it opens at the centre of the element’s visible bounds intersected with the viewport, and with neither it opens one pixel from the viewport’s top-left corner. This is a reading of the source, not a second measurement.

The keyboard path is not the same everywhere. Shift+F10 produced no contextmenu event in either browser, and the Menu key produced one only in Chromium. I did not run Windows or Linux, and I did not run the keys in Safari. Treat those as open and test them on the platforms you support.

The conclusion for a component is short. Whenever an element had the focus, the contextmenu event in these runs came with a point on or next to that element. The keys do not always produce that event, so a menu that should work from the keyboard everywhere has to listen for the keys itself, and then it has to choose the point itself.

Two common answers and where they fail

Anchor the menu to the area. The menu belongs to an area: a table, a file list, a canvas. With no pointer, the area’s own box is the nearest thing to anchor to. That works while the area fits in the window. I ran it on a 60-row table in a 700 px window, with the menu anchored to the table’s start corner through Floating UI with its flip, shift and size middleware. Scrolled so the table ran past both edges of the window, the menu opened above the window, out of sight. With the table’s bottom edge just below the window it opened under that edge, out of sight again. Flipping does not help when neither side of the reference is on the screen. A keyboard user pressed the key and the focus moved into a menu they could not see.

Use the focused element’s rectangle. Closer, because the menu now opens at the row the user is on. But getBoundingClientRect() describes the whole element, including the part that is scrolled out of a container or lies outside the window. For a row half hidden under the bottom edge of a scrolling panel, the centre of its rectangle is on the edge or beyond it. For a row the user scrolled away from with the mouse wheel and left focused, the rectangle is entirely outside the panel, and the menu opens over unrelated content or off the screen.

The rule

Open the menu at the centre of the visible part of the focused element. The centre, because it is the one point that is certainly on the element and that the user can connect to it whatever its size; a corner of a half-hidden row may be the hidden one.

  • The visible part is the element’s rectangle clipped by every ancestor that clips its content, and then by the window.
  • When the focused element has no visible part, use the visible part of the area instead. The user asked for the area’s menu; it should open where they can see the area.
  • When the area has no visible part either, open in the middle of the window.
  • When the focus is not inside the area, the keys do nothing, because the listener lives on the area.

Clipping by scrolling ancestors goes one step further than what I measured in Chromium, which clipped by the window. I chose it because a point outside the panel belongs to a different part of the page, and a menu that opens there reads as that part’s menu.

For a contextmenu event, use the event’s point as it is. For the mouse it is the pointer. For a screen reader command, or a browser that turns the Menu key into the event, the browser already picked a point on the element, and in Chromium it scrolled the element into view first. That leaves one case where the browser’s point is worse than this rule: an element taller than its scroller. I accept it there rather than second-guess an event that carries a position.

The visible centre

The function walks up the ancestors, narrows the rectangle wherever an ancestor clips, and returns null when nothing is left.

function visibleCenter(element) {
  let { top, right, bottom, left } = element.getBoundingClientRect()
  const root = document.documentElement

  for (let node = element.parentElement; node && node !== root; node = node.parentElement) {
    if (node === document.body) continue

    const { overflowX, overflowY } = getComputedStyle(node)
    const box = node.getBoundingClientRect()
    const scaleX = box.width / node.offsetWidth || 1
    const scaleY = box.height / node.offsetHeight || 1

    if (overflowX !== 'visible') {
      const start = box.left + node.clientLeft * scaleX
      left = Math.max(left, start)
      right = Math.min(right, start + node.clientWidth * scaleX)
    }

    if (overflowY !== 'visible') {
      const start = box.top + node.clientTop * scaleY
      top = Math.max(top, start)
      bottom = Math.min(bottom, start + node.clientHeight * scaleY)
    }
  }

  left = Math.max(left, 0)
  top = Math.max(top, 0)
  right = Math.min(right, root.clientWidth)
  bottom = Math.min(bottom, root.clientHeight)

  return right > left && bottom > top
    ? { x: (left + right) / 2, y: (top + bottom) / 2 }
    : null
}

Details that matter:

  • Each axis is checked on its own. A wide table in a panel with overflow-x: auto is clipped left and right; the browser computes the other axis to auto as well in that case, but overflow-x: clip can leave the other axis visible.
  • The clip is the padding box, which is what clientLeft, clientTop, clientWidth and clientHeight describe: inside the border and without a scrollbar that takes space. A point under a scrollbar is not a visible part of the row.
  • The client sizes are layout sizes, so they are multiplied by the ratio of the ancestor’s rendered size to its layout size. Without that, a panel inside something scaled, a zoomed preview for example, clips at the wrong place.
  • <html> and <body> are skipped. In the usual page their overflow belongs to the window, and the window is handled at the end.
  • Any value other than visible clips: hidden, clip, auto and scroll.

The function computes an intersection of rectangles, not what is painted, and that has limits you should know before copying it:

  • It treats every clipping ancestor as clipping the element. That is not true for an element with position: fixed, or an absolutely positioned one whose containing block is outside the clipping ancestor.
  • It does not see what covers the element. A row half under a sticky table header or a fixed page header gets a centre that may be under that header.
  • A rotated scroller is clipped by an approximation of its box.
  • It does not cross an <iframe> or a shadow root, and it does not know about clip-path, contain: paint, overflow-clip-margin or a <body> that scrolls on its own.
  • The window is the layout viewport. On a page the user has pinch-zoomed, the part on the screen is smaller; window.visualViewport describes it.

Placing the menu at a point

The menu is position: fixed, so the point’s window coordinates are its left and top. When the menu would cross the right or bottom edge of the window, it opens to the other side of the point.

function placeAt(menu, { x, y }) {
  const { clientWidth, clientHeight } = document.documentElement
  const { width, height } = menu.getBoundingClientRect()
  const left = x + width > clientWidth ? x - width : x
  const top = y + height > clientHeight ? y - height : y

  menu.style.left = `${Math.max(0, left)}px`
  menu.style.top = `${Math.max(0, top)}px`
}
.orders {
  height: 18rem;
  overflow: auto;
}

.context-menu {
  position: fixed;
  margin: 0;
  padding: 0.25rem 0;
  max-height: 100vh;
  overflow-y: auto;
  list-style: none;
}

This is positioning only; the menu still needs a background, a border and a z-index from your design. Put the menu element directly in <body>, outside the area. An ancestor with a transform, a filter or contain: paint, among others, would turn position: fixed into positioning against that ancestor, and the coordinates would no longer be window coordinates. An area inside a modal <dialog> needs the menu inside that dialog. The menu must be measurable when placeAt runs, so it is shown first and positioned second, in the same task; the browser paints only the final position.

The menu

The markup is an area that can hold the focus, rows that can hold it too, and a menu next to it. Every row is a tab stop here to keep the example short; a real list or grid keeps one tab stop and moves between rows with the arrow keys.

<div class="orders" id="orders" tabindex="-1">
  <table>
    <tbody>
      <tr tabindex="0"><td>Order 1001</td><td>Paid</td></tr>
      <tr tabindex="0"><td>Order 1002</td><td>Pending</td></tr>
      <tr tabindex="0"><td>Order 1003</td><td>Refunded</td></tr>
    </tbody>
  </table>
</div>

<ul class="context-menu" id="order-menu" role="menu" aria-label="Order actions" tabindex="-1" hidden>
  <li role="none"><button type="button" role="menuitem" tabindex="-1">Open</button></li>
  <li role="none"><button type="button" role="menuitem" tabindex="-1">Duplicate</button></li>
  <li role="none"><button type="button" role="menuitem" tabindex="-1">Archive</button></li>
</ul>

The controller ties the two together:

function createContextMenu(area, menu, onSelect) {
  let target = null
  let targetAt = ''
  let returnTo = null

  const items = () => [...menu.querySelectorAll('[role="menuitem"]')]

  const positionOf = element => {
    const { left, top } = element.getBoundingClientRect()
    return `${left},${top}`
  }

  function open(point, openedFor, focusFirstItem) {
    if (menu.hidden) {
      const active = document.activeElement
      returnTo = area.contains(active) ? active : null
      menu.hidden = false
    }

    target = openedFor
    targetAt = positionOf(openedFor)
    placeAt(menu, point)
    menu.focus()
    if (focusFirstItem) items()[0]?.focus()
  }

  function close() {
    if (menu.hidden) return

    menu.hidden = true
    const focusTarget = returnTo?.isConnected ? returnTo : area
    returnTo = null
    focusTarget.focus({ preventScroll: true })
  }

  area.addEventListener('contextmenu', event => {
    event.preventDefault()
    open({ x: event.clientX, y: event.clientY }, event.target, event.button === -1)
  })

  area.addEventListener('keydown', event => {
    if (event.key !== 'ContextMenu' && !(event.key === 'F10' && event.shiftKey)) return

    event.preventDefault()
    const { clientWidth, clientHeight } = document.documentElement
    const point = visibleCenter(event.target) ??
      visibleCenter(area) ??
      { x: clientWidth / 2, y: clientHeight / 2 }
    open(point, event.target, true)
  })

  menu.addEventListener('contextmenu', event => event.preventDefault())

  menu.addEventListener('keydown', event => {
    const list = items()
    const index = list.indexOf(document.activeElement)

    if (event.key === 'Tab') {
      close()
      return
    }

    if (event.key === 'Escape') {
      close()
    } else if (event.key === 'ArrowDown') {
      list[(index + 1) % list.length]?.focus()
    } else if (event.key === 'ArrowUp') {
      list[index <= 0 ? list.length - 1 : index - 1]?.focus()
    } else {
      return
    }

    event.preventDefault()
  })

  menu.addEventListener('click', event => {
    const item = event.target.closest('[role="menuitem"]')
    if (!item || item.getAttribute('aria-disabled') === 'true') return

    const openedFor = target
    close()
    onSelect?.(item, openedFor)
  })

  document.addEventListener('pointerdown', event => {
    if (!menu.contains(event.target)) close()
  })

  document.addEventListener('scroll', () => {
    if (!menu.hidden && positionOf(target) !== targetAt) close()
  }, true)
}
createContextMenu(
  document.querySelector('#orders'),
  document.querySelector('#order-menu'),
  (item, target) => console.log(item.textContent, target.closest('tr'))
)

What each part is there for:

  • The keys are handled on keydown, and the default is prevented. In Chromium this kept the browser from sending its own contextmenu event for the Menu key, so the menu opens once, at the point this code chose. Ctrl held with Shift+F10 opens the menu too.
  • contextmenu inside the menu is prevented and otherwise ignored. A second Shift+F10 with the focus on a menu item, on a platform that turns it into the event, would target the item, and nothing else would prevent it.
  • The focus goes to the menu first and then, after a key, to the first item. A keyboard user expects to act with the next key press. After a right-click no item should look chosen before the user picks one, but the focus still has to be inside the menu so that the arrow keys and Escape work; that is why the <ul> has tabindex="-1". Focusing the menu first also covers a first item that is hidden and a menu with no usable item: the focus is inside the menu either way, and Escape closes it.
  • button === -1 counts as the keyboard. That is what Chromium reported for the Menu key and for the VoiceOver command. Firefox and Safari reported 2 for the same command, so there the focus lands on the menu, not on the first item. I did not check what a screen reader announces in either case.
  • returnTo is read only when the menu opens from closed. A real second right-click never meets this guard: its pointerdown closes the menu, the press moves the focus to the row under the pointer, and the menu opens from closed for that row. The guard is for a contextmenu event that arrives with no pointerdown while the menu is open, a screen reader command for example; the focus is inside the menu then, and reading it again would lose the row.
  • The focus returns to the element that had it, not to the area. In a table, a focus that returns to the area sends the next Tab to the first row, fifty rows above where the user was. The area is the fallback when the row was removed while the menu was open, which is why the area has tabindex="-1".
  • Returning the focus passes preventScroll: true. Closing a menu should not move the page: a row that was half visible stays half visible. The arrow keys call focus() without it on purpose, so a long menu scrolls to the focused item.
  • Tab closes the menu and moves on. This is what the ARIA menu pattern asks for: Escape returns to where the menu was opened, Tab and Shift+Tab leave. The handler closes the menu, which puts the focus back on the row, and does not prevent the key, so the browser then moves the focus from the row to the next or previous tab stop in the same key press.
  • An unavailable item is marked with aria-disabled="true", not disabled. The same pattern keeps unavailable items reachable with the arrow keys, so that a screen reader user learns the action exists. A <button disabled> cannot take the focus, so the item keeps the focus and the click handler ignores it; the menu stays open.
  • A scroll that moves the target closes the menu. A fixed menu stays put while the row it belongs to scrolls away. The listener is registered for the capture phase because scroll does not bubble from a scrolling panel, and it compares the target’s position with the one stored on opening. A chat pane scrolling elsewhere on the page, a scroll event that arrives just after the menu opened and scrolling inside a long menu all leave the target where it was, so the menu stays. The other honest choice is to block scrolling while the menu is open. Leaving the menu floating over a different row is the one to avoid.
  • onSelect gets the element the menu was opened for: the focused element after a key, the event’s target after a right-click, hence closest('tr').

What the listing leaves out, and a product needs:

  • Home, End and typing a letter to jump to an item.
  • A way to remove the two document listeners when the area goes away.
  • Leaving the browser’s own menu alone where the user needs it: in a text field, an editable cell or over selected text inside the area.
  • Closing when the focus leaves the menu by other means, and on window resize.
  • One menu shared by several areas.

How to test it

Positions are easy to assert because the rule gives one number per case. These are the cases I run against the code above, in Chromium and Firefox, on a page with a long table inside a scrolling panel. Clicks and wheel scrolling are real input, and the cases that scroll wait for the menu’s state, not for a fixed time.

  1. Focused row inside the panel, Shift+F10: the menu’s top-left corner is at the centre of the part of the row the panel shows, and the first item has the focus. The same with the Menu key, and in Chromium no contextmenu event reaches the document.
  2. Row half under the bottom edge of the panel: the corner is at the centre of the visible half, inside the panel.
  3. Row wider than the panel, with and without a scrollbar that takes space: the corner is at the centre of the visible width.
  4. Page scrolled so the focused row is cut by the top of the window: the corner is at the centre of the part inside the window.
  5. Focused row scrolled out of the panel: the corner is at the centre of the panel.
  6. Panel scrolled out of the window with a row still focused: the menu opens in the middle of the window.
  7. Panel scaled to half its size: both axes are clipped at the scaled edges.
  8. overflow-x: clip with a visible vertical axis clips horizontally only.
  9. Right-click on a row: the corner is at the pointer and the focus is on the menu, not on an item. A contextmenu event with button -1 puts the focus on the first item.
  10. Right-click near the bottom-right corner of the window: the whole menu is inside the window.
  11. Escape after a keyboard open: the focus is back on the row that had it, and a half-visible row is still half visible.
  12. Right-click on one row, then on another, then Escape: the menu moved to the second point and the focus is on the second row. Two contextmenu events with no pointerdown between them: the focus returns to the row that had it before the first.
  13. First item with aria-disabled="true": it has the focus, and Enter on it neither closes the menu nor calls onSelect. First item hidden, or no items at all: the focus is on the menu and Escape closes it.
  14. The focused row is removed while the menu is open, then Escape: the focus is on the area.
  15. contextmenu on a menu item is prevented.
  16. F10 without Shift opens nothing.
  17. Wheel scrolling over the panel or the page closes the menu. Wheel scrolling in an unrelated scroller does not, and neither does a scroll event from a scroll that happened just before the menu opened.
  18. Enter on an item closes the menu and calls onSelect with the item and the row; a press outside closes it.
  19. Tab in the menu closes it and the focus is on the row after the one that had it; Shift+Tab ends on the row before it.

Each rule also has a mutation: I break one line of the article’s code (drop the ancestor clipping, drop the fallback to the area, skip the first item after a key, forget preventScroll on the way back) and check that at least one case fails. A case that still passes with the rule removed was not testing the rule.

Then do by hand what a script cannot: press the real keys on every platform you support, and open the menu with your screen reader’s own context menu command.

What other libraries do

I read two context menu implementations to see how they choose the point; I did not run them. Radix UI’s @radix-ui/react-context-menu 2.4.1 (dist/index.mjs) and Zag’s @zag-js/menu 1.49.0 (dist/menu.connect.mjs) both open from the trigger’s contextmenu event, plus a long press for touch, and anchor the menu to that event’s clientX and clientY. Neither trigger listens for Shift+F10 or the Menu key. That leaves the keyboard path to the browser and the operating system; in the runs above, that path was the Menu key in Chromium only.

What I did not check

  • Windows and Linux, in any browser: whether the keys produce contextmenu, where its point is, and whether preventing keydown stops it there.
  • Safari: neither the keys nor the code in this guide were run there. Run the cases above in it before you ship.
  • NVDA, JAWS, Narrator and TalkBack. The VoiceOver result covers a fully visible row; I did not measure its point on a clipped one, or what it announces when the menu opens.
  • Whether a browser shows its own menu on top when contextmenu inside the menu is not prevented.
  • A contextmenu event with both coordinates at zero. I did not see one, so the code above has no branch for it.
  • Right-to-left pages and long-press on touch screens.

In CoreUI

The Context Menu in CoreUI v6 does this in its JavaScript, React and Vue editions. Shift+F10 and the Menu key open the menu at the centre of the visible part of the focused element, with the visible part of the area as the fallback; when neither is visible, the menu is anchored to the area itself, not to the middle of the window. Its clipping treats a scrolling ancestor as clipping both axes. A contextmenu event opens the menu at the event’s point, unless both coordinates are zero; then the menu is anchored to the area. After a key the first item has the focus, after a pointer the menu does, and closing the menu returns the focus to the element inside the area that had it. Its arrow keys skip disabled items, where the listing above keeps them reachable.

About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.