Element: beforematch event
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 addEventListener():
addEventListener("beforematch", (event) => { })
Alternatively, assign to the event handler property of the interface:
onbeforematch = (event) => { }
Event type
A generic Event.
Usage notes
- Fire a
beforematchevent on the hidden element - Remove the
hiddenattribute from the element - Scroll to the element
Examples
Using beforematch
In this example, we have two div elements.
The first is visible, while the second has the hidden="until-found" and id="until-found-box" attributes.
The element with a until-found-box id has a dotted red border and a gray background.
We also have a link that targets the "until-found-box" fragment and JavaScript that listens for the beforematch event firing on that hidden element.
The event handler changes the text content of the box to illustrate an action that can occur when the hidden until found state is about to be removed.
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;
}
div#until-found-box {
color: red;
border: 5px dotted red;
background-color: lightgray;
}
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 element in the hidden until found state.
The beforematch event fires, the text content is updated, and then the element's content is displayed (the hidden attribute is removed).
To run the example again, click "Reload".
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
Browser compatibility
See also
谢谢你的反馈!