get highlighted and selected text with cursor in JavaScript

HOW TO GET HIGHLIGHTED AND SELECTED TEXT WITH CURSOR IN JavaScript

Use of getSelection() in JavaScript to get highlighted and selected text with cursor

Now we can use getSelection() method in the window object to access the text that the user has selected with the cursor. Developers can create dynamic, interactive, and user-friendly web applications by using this method getSelection()

Understanding the Basics of getSelection()

The getSelection() method is a part of the window object we can use to retrieve and manipulate the current text selection of a web application page. This method returns an object representing the range of text the user selects.

Syntax and Basic Usage

The syntax for using the getSelection() method is straightforward to get highlighted and selected text with cursor in JavaScript

var selection = window.getSelection();

This simple line of code grants access to the Selection object, which can then be used to perform a variety of operations.

Key Properties of the Selection Object

The Selection object returned by getSelection() has several important properties:

  • anchorNode: The node where the selection begins.
  • focusNode: The node where the selection ends.
  • anchorOffset: The number of characters from the start of the anchorNode where the selection begins.
  • focusOffset: The number of characters from the start of the focusNode where the selection ends.
  • isCollapsed: A boolean indicating whether the selection is collapsed (i.e., the start and end points are the same).
  • rangeCount: The number of ranges in the selection.

Manipulating the Selection

Once a Selection object is obtained, various methods can be employed to manipulate the selection:

  • addRange(range): Adds a Range object to the selection.
  • removeAllRanges(): Removes all ranges from the selection.
  • deleteFromDocument(): Deletes the selected text from the document.
  • toString(): Returns a string containing the text of the selection.

Practical Applications of getSelection()

Creating Interactive Text Highlighting

One of the most common uses of the getSelection() method is to implement text highlighting features. For instance, allowing users to highlight text on a webpage and save their highlights for future reference can significantly enhance user engagement.

Here’s a basic example of how to achieve this:

document.addEventListener('mouseup', function () {
    var selection = window.getSelection();
    if (!selection.isCollapsed) {
        var range = selection.getRangeAt(0);
        var highlightSpan = document.createElement('span');
        highlightSpan.style.backgroundColor = 'yellow';
        range.surroundContents(highlightSpan);
        selection.removeAllRanges();
    }
});

Enabling Contextual Menus

Another powerful application is enabling contextual menus based on the selected text. This can be particularly useful for providing additional options such as searching the selected text, copying it, or even translating it.

Here’s a simple implementation:

document.addEventListener('mouseup', function (event) {
    var selection = window.getSelection();
    if (!selection.isCollapsed) {
        var selectedText = selection.toString();
        var contextMenu = document.getElementById('contextMenu');
        contextMenu.style.top = event.clientY + 'px';
        contextMenu.style.left = event.clientX + 'px';
        contextMenu.style.display = 'block';
        document.getElementById('searchOption').onclick = function () {
            window.open('https://www.google.com/search?q=' + encodeURIComponent(selectedText));
        };
    }
});
document.addEventListener('click', function () {
    var contextMenu = document.getElementById('contextMenu');
    contextMenu.style.display = 'none';
});

Implementing Real-Time Text Analysis

For websites that require real-time text analysis, such as grammar checking or keyword density analysis, the getSelection() method is invaluable. By continuously monitoring the selected text, developers can provide instant feedback and suggestions.

Example for a basic keyword density checker:

document.addEventListener('selectionchange', function () {
    var selection = window.getSelection();
    if (!selection.isCollapsed) {
        var selectedText = selection.toString();
        var keyword = 'JavaScript';
        var keywordCount = (selectedText.match(new RegExp(keyword, 'gi')) || []).length;
        document.getElementById('keywordDensity').innerText = `Keyword "${keyword}" appears ${keywordCount} times in the selected text.`;
    }
});

Advanced Techniques with getSelection()

Custom Range Creation

Sometimes, you might need to create and manipulate custom text ranges programmatically. The getSelection() method, combined with the Range interface, makes this possible.

Example of creating a custom range:

var range = document.createRange(); 
var startNode = document.getElementById('startElement'); 
var endNode = document.getElementById('endElement'); 
range.setStart(startNode, 0); 
range.setEnd(endNode, endNode.childNodes.length); 
var selection = window.getSelection(); 
selection.removeAllRanges(); 
selection.addRange(range);

Saving and Restoring Selections

In some applications, it’s crucial to save the user’s selection and restore it later. This can be particularly useful in text editing applications where users need to retain their selection across different sessions.

Example of saving and restoring a selection:

function saveSelection() {
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
        var range = selection.getRangeAt(0);
        localStorage.setItem('savedSelection', JSON.stringify({
            startContainerPath: getDomPath(range.startContainer),
            startOffset: range.startOffset,
            endContainerPath: getDomPath(range.endContainer),
            endOffset: range.endOffset
        }));
    }
}
function restoreSelection() {
    var savedSelection = JSON.parse(localStorage.getItem('savedSelection'));
    if (savedSelection) {
        var range = document.createRange();
        range.setStart(getElementByDomPath(savedSelection.startContainerPath), savedSelection.startOffset);
        range.setEnd(getElementByDomPath(savedSelection.endContainerPath), savedSelection.endOffset);
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}
function getDomPath(el) {
    var stack = [];
    while (el.parentNode != null) {
        var sibCount = 0;
        var sibIndex = 0;
        for (var i = 0; i < el.parentNode.childNodes.length; i++) {
            var sib = el.parentNode.childNodes[i];
            if (sib.nodeName == el.nodeName) {
                if (sib === el) {
                    sibIndex = sibCount;
                } sibCount++;
            }
        }
        stack.unshift(el.nodeName.toLowerCase() + (sibCount > 1 ? ':nth-of-type(' + (sibIndex + 1) + ')' : ''));
        el = el.parentNode;
    }
    return stack.join('>');
}
function getElementByDomPath(path) {
    return document.querySelector(path);
}

Best Practices for Using getSelection() to get highlighted and selected text with cursor in JavaScript

Cross-Browser Compatibility

While the getSelection() method is widely supported, always ensure your implementation is tested across different browsers. Some older versions of browsers may not fully support all features of the Selection API.

Security Considerations

When manipulating selections and interacting with user-provided text, always consider security implications such as Cross-Site Scripting (XSS) attacks. Sanitize and validate any user inputs that are incorporated into your application.

Performance Optimization

Be mindful of performance, especially when dealing with large documents or frequent selection changes. Optimize your code to handle selections efficiently without causing noticeable lag or delays for the user.

Conclusion

Here, we have covered multiple scenarios by using getSelection() method to get highlighted and selected text with cursor in JavaScript. getSelection() the method is a very important method for enhancing user interaction on your web application. We can go through this article to understand about its capabilities and uses. with the use of the getSelection() method, the developer can create a dynamic, user-friendly web application.

Some useful links:
React Hooks Interview Questions: https://tekody.com/react-hooks-interview-questions/

Leave a Comment

Your email address will not be published. Required fields are marked *