Get Started
The custom-highlight
library is a set of lifecycle hooks for highlighting words or even larger phrases within a body of text.
Under the hood, it uses the native CSS Custom Highlight API as a mechanism for styling text ranges, all without making any alterations to the DOM structure.
Installation
sh
npm install custom-highlight
sh
pnpm add custom-highlight
sh
yarn add custom-highlight
sh
bun add custom-highlight
CDN
html
<script src="https://unpkg.com/custom-highlight"></script>
html
<script src="https://cdn.jsdelivr.net/npm/custom-highlight"></script>
It will be exposed globally as window.CustomHighlight
.
Usage
Here is a very basic example that will highlight the words “brown fox” in the paragraph.
html
<p id="gettingStarted">The quick brown fox jumps over the lazy dog.</p>
<script type="module">
import CustomHighlight from 'custom-highlight';
const element = document.getElementById('gettingStarted');
const options = { value: 'brown fox' };
if (element) {
CustomHighlight
.created(element, options)
.beforeMount(element, options)
.mounted(element, options);
}
</script>
<style>
::highlight(default) {
background-color: yellow;
color: black;
}
</style>
The quick brown fox jumps over the lazy dog.
This works just fine in a static webpage, but frameworks that dynamically render content by manipulating the DOM (e.g. Vue, React, Svelte, etc.) will require additional effort in conforming to their component lifecycles.