Sling Academy
Home/JavaScript/Interactive Annotations Using the CSS Custom Highlight API in JavaScript

Interactive Annotations Using the CSS Custom Highlight API in JavaScript

Last updated: December 12, 2024

Interactive web applications have been all the rage in recent years, allowing users to have a dynamic and engaging experience. A lesser-known but powerful feature that can enhance such interactivity is the CSS Custom Highlight API. This API enables developers to highlight parts of a document dynamically, giving more control over how text is presented. In this article, we explore how you can use this API alongside JavaScript to create interactive annotations in your web applications.

The Browser's native selection has been long available, which allows users to highlight text. However, the Custom Highlight API provides more flexibility, enabling developers to define their highlight types and styles. Let’s dive into how you can use these features effectively.

Understanding the CSS Custom Highlight API

The CSS Custom Highlight API allows the definition of pseudo-elements that apply to text paragraphs. You can create named highlights and apply various CSS styles to these highlights. This way, you can handle multiple styled highlights and even animations.

Creating a Custom Highlight

First, we need to define and apply a custom highlight. Here's a simple example:

// Create a new highlight registry
const highlightRegistry = CSS.highlights;

// Define our custom highlight
const customHighlight = new Highlight();

// Use a range of text to highlight
let range = new Range();
range.setStart(document.getElementById('content'), 0);
range.setEnd(document.getElementById('content'), 1);
customHighlight.add(range);

// Register our custom highlight
highlightRegistry.set('myHighlight', customHighlight);

In this example, we create a new highlight and specify the text range we want to highlight. After setting the parameters, we register our highlight using the highlightRegistry.set method.

Styling the Highlight

Once the highlight is registered, you can apply CSS to style it:

::highlight(myHighlight) {
  background-color: yellow;
  color: black;
}

This snippet applies a yellow background and black text color to the highlighted text, using the ::highlight() pseudo-element.

Interactive Annotations with JavaScript

With custom highlights, we can implement interactive features, such as tooltips or comment boxes. Let’s create an annotation system wherein users can click highlights to see commentary or information pop-ups.

Adding Event Listeners

To make the highlights interactive, we can attach event listeners:

document.addEventListener('click', (e) => {
  if (e.target.closest('::highlight(myHighlight)')) {
    showPopup(e.clientX, e.clientY);
  }
});

function showPopup(x, y) {
  const popup = document.createElement('div');
  popup.style.position = 'absolute';
  popup.style.left = `${x}px`;
  popup.style.top = `${y}px`;
  popup.textContent = 'More information here';
  document.body.appendChild(popup);
}

This script listens for clicks on any element with our custom highlight. When clicked, it calls showPopup, placing a new information box at the click's coordinates.

Enhancing Usability

Beyond basic highlights and simple pop-ups, there are numerous ways to improve usability:

  • Animations: Use CSS transitions to animate the highlight changes, offering a more visually appealing experience.
  • Dynamic Content: Load annotations dynamically from a server, based on user interactions to minimize initial loading time.

Incorporating these suggestions can make the interaction with annotations even more engaging. For instance, consider loading detailed insights or notes as users hover over highlighted sections for a more informative interaction.

Conclusion

The CSS Custom Highlight API combined with JavaScript offers versatile opportunities to create interactive text-based features. Whether you want simple text highlighting for reading ease or complex interactive elements, understanding and utilizing this API can significantly enhance the UX of your web applications. Experiment with your own configurations and see what creative patterns you can create.

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

Previous Article: Define Custom Highlights with 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