Skip to content

Web Component Recipe

Here is a simple example showing how to use custom-highlight in a custom element's lifecycle callbacks.

ts
import CustomHighlight from 'custom-highlight';

export class CustomHighlightZone extends HTMLElement {
  static observedAttributes = ['search'];

  connectedCallback() {
    const value = this.getAttribute('search');

    if (value) {
      CustomHighlight
        .created(this, { value })
        .beforeMount(this, { value })
        .mounted(this, { value });
    }
  }

  attributeChangedCallback(name: string, oldValue: string, value: string) {
    if (this.isConnected && name === 'search') {
      CustomHighlight
        .beforeUpdate(this, { value, oldValue })
        .updated(this, { value, oldValue });
    }
  }

  disconnectedCallback() {
    const value = this.getAttribute('search');

    if (value) {
      CustomHighlight.unmounted(this, { value });
    }
  }
}
html
<script type="module">
  import { CustomHighlightZone } from './CustomHighlightZone.js';
  customElements.define('custom-highlight-zone', CustomHighlightZone);
</script>

<custom-highlight-zone search="brown fox">
  The quick brown fox jumps over the lazy dog.
</custom-highlight-zone>

<style>
  ::highlight(default) {
    background-color: yellow;
    color: black;
  }
</style>

Released under the MIT License.