docs.rodeo

MDN Web Docs mirror

Element: beforematch event

{{APIRef}} {{SeeCompatTable}} 

An element receives a beforematch event when it is in the hidden until found state and the browser is about to reveal its content because the user has found the content through the “find in page” feature or through fragment navigation.

Syntax

Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}} , or set an event handler property.

addEventListener("beforematch", (event) => { })

onbeforematch = (event) => { }

Event type

A generic {{domxref("Event")}} .

Usage notes

The HTML hidden attribute accepts a value until-found: when this value is specified, the element is hidden but its content will be accessible to the browser’s “find in page” feature or to fragment navigation. When these features cause a scroll to an element in a “hidden until found” subtree, the browser will:

Examples

Using beforematch

In this example we have:

We also have some JavaScript that listens for the beforematch event firing on the hidden until found element. The event handler changes the text content of the box.

HTML

<a href="#until-found-box">Go to hidden content</a>

<div>I'm not hidden</div>
<div id="until-found-box" hidden="until-found">Hidden until found</div>
<button id="reset">Reset</button>

CSS

div {
  height: 40px;
  width: 300px;
  border: 5px dashed black;
  margin: 1rem 0;
  padding: 1rem;
  font-size: 2rem;
}
#until-found-box {
  scroll-margin-top: 200px;
}

JavaScript

const untilFound = document.querySelector("#until-found-box");
untilFound.addEventListener(
  "beforematch",
  () => (untilFound.textContent = "I've been revealed!"),
);
document.querySelector("#reset").addEventListener("click", () => {
  document.location.hash = "";
  document.location.reload();
});

Result

Clicking the “Go to hidden content” button navigates to the hidden-until-found element. The beforematch event fires, the text content is updated, and then the element’s content is displayed.

To run the example again, click “Reload”.

{{EmbedLiveSample("Using beforematch", "", 300)}} 

If your browser does not support the "until-found" enumerated value of the hidden attribute, the second <div> will be hidden (as hidden was boolean prior to the addition of the until-found value).

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN