Sling Academy
Home/JavaScript/Highlight Custom Ranges with the JavaScript Selection API

Highlight Custom Ranges with the JavaScript Selection API

Last updated: December 13, 2024

In modern web applications, the need to interactively manipulate and display text selections is increasingly important. The JavaScript Selection API provides developers with the functionality to precisely manage and highlight text selections within documents. In this article, we'll explore how to highlight custom ranges in a document using the JavaScript Selection API. We'll cover the concepts and provide code examples for a thorough understanding.

Understanding the Selection API

The Selection API is part of the larger group of APIs in the Web API suite designed to manage the behaviour of user selection. It allows for the retrieval of the currently highlighted text or a customized portion of text in a web page, making modifications, and dynamically interacting with the highlighted content.

Key Objects in Selection API

The main objects used in the Selection API are:

  • Selection: Represents the range of text selected by the user or the current focus highlight in a document.
  • Range: Represents a fragment of a document that can be comprised of multiple selected or unselected nodes.

Basic Usage Example

As a starting point, let's extract simple selected text using JavaScript. Here is an example:

document.addEventListener('mouseup', () => {
  const selection = window.getSelection();
  console.log(selection.toString());
});

In this example, when a user finishes highlighting text on the page by releasing the mouse button, this code logs the selected text to the console.

Highlighting Custom Ranges

To highlight specific text within a page programmatically, custom Range objects can be created. Let’s see a sample implementation:

function highlightRange() {
  const range = document.createRange();
  const startNode = document.getElementById('para1');
  const endNode = document.getElementById('para2');

  // Defining the start and end containers
  range.setStart(startNode.firstChild, 0);
  range.setEnd(endNode.firstChild, 2);

  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);

  // Styling the selected range
  document.getSelection().focusNode.parentNode.style.backgroundColor = 'yellow';
}

highlightRange();

In this code snippet, a custom range is specified between two elements identified by their IDs, para1 and para2. We apply a yellow background to highlight the range. Note that text nodes are targeted with startNode.firstChild and endNode.firstChild.

Further Enhancements

Custom styling can be applied to the highlighted text. For dynamic interactions, JavaScript allows event listeners to respond when selections get modified:

document.addEventListener('selectionchange', () => {
  console.log('Selection has changed!');
  // Other dynamic operations can be added here.
});

Including additional event handlers broadens interaction opportunities for selected content beyond static highlights. Asynchronous operations, such as text analysis or server interactions, can be triggered on selection change.

Conclusion

Utilizing the JavaScript Selection API enables nuanced control over user interactions with document text. By leveraging Selection and Range objects, developers can create coherent and dynamic experiences in web applications. With the basics covered here, further exploration into complex text management and customized styling strategies are within reach for more advanced implementations.

Next Article: Implement Custom Copy and Context Menus via JavaScript Selection

Previous Article: Select Text and Elements Using the Selection 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