Sling Academy
Home/JavaScript/Add Contextual Emphasis with the CSS Custom Highlight API in JavaScript

Add Contextual Emphasis with the CSS Custom Highlight API in JavaScript

Last updated: December 12, 2024

The CSS Custom Highlight API is a relatively new addition to the web development toolkit that allows developers to style portions of text in the browser. This feature is particularly useful for creating interactive educational content, enhancing accessibility, or even personalizing user experiences. In this article, we'll explore how to use the Custom Highlight API in conjunction with JavaScript to add contextual emphasis to text within your web applications.

Understanding the CSS Custom Highlight API

The CSS Custom Highlight API allows for the definition of custom text highlight styles using CSS. It works similarly to pseudo-elements, like ::selection, but gives developers more flexibility and power to define specific CSS rules that target custom ranges of text.

Getting Started with the Custom Highlight API

To begin using the Custom Highlight API, you first need to identify the text ranges you want to style. This can be accomplished using JavaScript. Then, you apply custom styles through custom properties defined within your CSS.

Here is a basic example:

<!-- HTML -->
<p>This is a simple text for demonstration purposes.</p>
// JavaScript
if ('CSS' in window && CSS.highlights && CSS.highlights.set) {
    const highlight = new Highlight();
    const range = new Range();

    // Select the text range
    range.setStart(document.querySelector('p').firstChild, 0);
    range.setEnd(document.querySelector('p').firstChild, 8);

    // Add the range to the highlight
    highlight.add(range);

    // Register the highlight type
    CSS.highlights.set('exampleHighlight', highlight);
}

In this snippet, a Highlight object is created and a text range is defined. The range specifies the start and end points of the text that should be highlighted. Finally, this highlight is registered with a custom name, 'exampleHighlight'.

Styling the Highlighted Text

To apply custom styles, define them using a custom CSS pseudo-element associated with the highlight name:

/* CSS */
::highlight(exampleHighlight) {
    background-color: yellow;
    color: black;
    font-weight: bold;
}

This CSS snippet targets the custom named highlight exampleHighlight, applying a yellow background with bold black text. Changing these values will alter the appearance of your highlighted text.

Use Cases and Dynamic Highlights

The true power of the Custom Highlight API lies in its ability to work dynamically with JavaScript. This enables you to change highlights based on user interactions, real-time data processing, and much more.

For example, consider a search functionality that highlights matched search terms:

function highlightSearchTerm(term) {
    const paragraphs = document.querySelectorAll('p');
    paragraphs.forEach(p => {
        const regex = new RegExp(term, 'gi');
        let match;
        const highlight = new Highlight();
        while ((match = regex.exec(p.textContent)) !== null) {
            const range = new Range();
            range.setStart(p.firstChild, match.index);
            range.setEnd(p.firstChild, match.index + match[0].length);
            highlight.add(range);
        }
        CSS.highlights.set('searchHighlight', highlight);
    });
}

In this function, the term is dynamically searched within each paragraph. For every match found, a range is created, and highlights are applied for each occurrence.

Conclusion

With the CSS Custom Highlight API, developers can enrich content and improve user interaction through stylized, dynamic text highlights. By leveraging JavaScript to define complex, interactive highlights, developers can create responsive, engaging content like never before. As the web continues to evolve, features like these will become pivotal in crafting sophisticated, user-centric web applications.

Next Article: Optimize Web Typography Using the CSS Font Loading API in JavaScript

Previous Article: Customize Underlines and Colors via the CSS Custom Highlight API in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration