How to close a menu on outside click — and why your modal closes when you select text

A user opened a modal with a form. Started selecting text in a field with the mouse. Missed slightly — released the button just past the modal's edge. And the modal closed. Along with everything they'd typed.
This is the classic "click outside" bug. The task looks simple: click away from the menu — close it. But it has three traps, and AI-written code usually falls into at least one. Let's go step by step — by the end you'll have a solution with none of the three.
Step 1. Check whether you need code at all
Browsers have learned to do this themselves. For dropdown menus and tooltips there's the popover attribute:
<button popovertarget="menu">Menu</button>
<div id="menu" popover>
<a href="/profile">Profile</a>
<a href="/logout">Log out</a>
</div>
Not a single line of JavaScript. A click outside closes the menu, so does Esc. Works in all modern browsers. By the way, if you need to pick one value from a list rather than a menu of actions — check out dropdown vs radio buttons first.
For modals there's <dialog closedby="any"> — close on backdrop click. But Safari doesn't support it yet. So modals on iPhone still need code. On we go.
Step 2. A "click outside" hook for React
The idea is simple. Put a listener on the whole document. On every press, ask: "was this press inside my menu?" If not — close it.
import { useEffect, useRef } from 'react'
function useClickOutside(onOutside) {
const ref = useRef(null)
useEffect(() => {
function handle(e) {
if (ref.current && !ref.current.contains(e.target)) {
onOutside()
}
}
document.addEventListener('pointerdown', handle)
return () => document.removeEventListener('pointerdown', handle)
}, [onOutside])
return ref
}
What matters here:
refis a reference to the menu's box in the DOM. Thecontainsmethod tells you whether the pressed element sits inside it.onOutsideis a callback: what to do on an outside click. Usually() => setOpen(false).- The
returninsideuseEffectremoves the listener once the menu is gone. Without it, listeners pile up with every open.
Step 3. Listen to pointerdown, not click
That's trap one. AI almost always writes 'click'. But the click event fires only after the mouse button is released.
Picture this: the menu has a "Delete" item. Clicking it removes it from the list. By the time the event reaches the document, that element is gone from the page. contains says "no, not inside" — and the menu closes, even though you clicked right in it.
pointerdown fires the moment you press. The element is still there, the check is honest. And it works for both mouse and finger.
Step 4. Fix closing on text selection
Trap two — the one we started with. It bites modals with a dark backdrop whose handler sits on the backdrop itself:
<div className="backdrop" onClick={(e) => {
if (e.target === e.currentTarget) close()
}}>
You pressed inside the modal and released on the backdrop. The browser sends click to the common ancestor of the two elements. The common ancestor of the modal and the backdrop is the backdrop. The e.target === e.currentTarget check passes, the modal closes.
The fix: remember where the press started.
const downOnBackdrop = useRef(false)
<div
className="backdrop"
onPointerDown={(e) => {
downOnBackdrop.current = e.target === e.currentTarget
}}
onClick={(e) => {
if (downOnBackdrop.current && e.target === e.currentTarget) close()
}}
>
Now the modal closes only if the press both started and ended on the backdrop.
Step 5. Don't let the button reopen the menu
Trap three. The menu is open. You press the same button to close it. Here's what happens:
pointerdownon the button — it's outside the menu → the menu closes.clickon the button — it toggles the state → the menu opens again.
It looks like the button is broken. The fix: put the ref on a shared wrapper holding both the button and the menu.
function Menu() {
const [open, setOpen] = useState(false)
const ref = useClickOutside(() => setOpen(false))
return (
<div ref={ref}>
<button onClick={() => setOpen(!open)}>Menu</button>
{open && <ul className="menu">…</ul>}
</div>
)
}
Now the button is "inside" — clicking it goes only to the toggle.
Step 6. Add Esc
Not everyone uses a mouse. Add a second listener in the same useEffect:
function onKey(e) {
if (e.key === 'Escape') onOutside()
}
document.addEventListener('keydown', onKey)
And remember to remove it in return, like the first one.
What you get
A menu and a modal that:
- close on a press anywhere outside and on
Esc; - don't close when you click an item that disappears immediately;
- don't lose the form if someone was selecting text and missed;
- open and close with one button without getting "stuck".
A ready prompt for AI: "Implement close-on-outside-click with pointerdown on document and a ref on a wrapper that includes the button. For the modal, close on backdrop only if pointerdown was on the backdrop too. Add Esc and listener cleanup."
Why doesn't it work when the menu is in a portal?
A portal renders the menu elsewhere in the document — say, straight into body. Then the wrapper's contains can't see it. Check both refs: the wrapper and the menu in the portal.
Can I just put a transparent layer over the whole screen?
You can, and people often do. But that layer swallows the first click: the user meant to tap a link next to the menu and only closed the menu. Popover and the hook above don't do that.
The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.





