The HTML onbeforematch event
The HTML onbeforematch attribute runs JavaScript when a hidden="until-found" element is about to be revealed by find-in-page or a fragment link. It is an inline handler for the beforematch event; in modern code prefer addEventListener('beforematch', …).
Overview
The onbeforematch event attribute runs JavaScript before hidden-until-found content is revealed. In JavaScript the event itself is named beforematch. Drop the on prefix when you call addEventListener.
It is fired on an element carrying hidden="until-found" when the browser is about to reveal it, for example because find-in-page, a fragment link or a scroll-to-text fragment matched inside it. Handling it lets you expand surrounding content before the browser scrolls to the match.
You can wire this up with the inline onbeforematch HTML attribute, but the modern, recommended approach is element.addEventListener('beforematch', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element onbeforematch="handler()">…</element>
element.addEventListener('beforematch', handler);
Best practices
- Prefer
element.addEventListener('beforematch', handler)over the inlineonbeforematchattribute; it separates behavior from markup and allows multiple handlers. - Prefer the native <dialog>, <details> and popover APIs that fire these events over hand-built widgets.
- Use the event to sync state, for example to lazy-load content when a panel opens.
- Keep these widgets accessible: manage focus and provide an accessible name.
Frequently asked questions
What is the onbeforematch event?
beforematch.Which elements fire this event?
hidden="until-found" set.How do I reveal the content myself?
hidden attribute in the handler, before the browser scrolls to the match.Should I use the onbeforematch attribute or addEventListener?
element.addEventListener('beforematch', …) in JavaScript. The inline onbeforematch attribute works but mixes behavior into the markup and allows only one handler per element.