JavaScript - Marking selected text: What are the options?

I am looking to implement a feature in JavaScript (without jQuery) that will allow me to highlight selected text with control points or markers (left and right). These markers should function similar to those on mobile phones, allowing me to extend the selection by dragging them. Here is an example of what I'm trying to achieve:

In my current demo (http://jsfiddle.net/henrichro/HJ482/), I have managed to grab the selected text using the following code snippet:

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    alert(text);
}

if (window.Event) document.captureEvents(Event.MOUSEUP);
document.onmouseup = getSelectionText;

Though this code retrieves the text successfully, I now aim to enhance it by adding markers around the selected text as described earlier.

Update 10/28/2013:

Following Dementic's guidance (see answer below), I have made progress and achieved a working version with markers using this new code: http://jsfiddle.net/henrichro/WFLU9/.

However, I am facing an issue when selecting more than one line of text, causing the markers to display incorrectly. Any suggestions on how to address this would be greatly appreciated.

Answer №1

Discovered a helpful solution at this link: How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?

Initially using a bit of Jquery, I managed to convert it to pure JS by removing the selectors and onclick function. You can view the updated example here: http://jsfiddle.net/3tvSL/83/

This feature highlights selected text with a yellow background, although additional work is required for side "Markers."

One suggestion is to use an absolute positioned div as the marker, and to facilitate dragging, utilize code like:

function expand(range) {
    if (range.collapsed) {
        return;
    }

    while (range.toString()[0].match(/\w/)) {
        range.setStart(range.startContainer, range.startOffset - 1);   
    }

    while (range.toString()[range.toString().length - 1].match(/\w/)) {
        range.setEnd(range.endContainer, range.endOffset + 1);
    }
}

This excerpt was taken from: Select whole word with getSelection

Furthermore, I discovered a functional JS library that precisely fulfills your needs... I recommend checking it out :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...

Error encountered when URLSearchParams attempts to add an array

Hi, I'm encountering a problem when attempting to send an array using URLSearchParams. Here is the code snippet in question: const worker = async(endpoint, method, parameters) => { let body; if (typeof parameters === 'object' &am ...

The left border is failing to appear on the Td element

When attempting to add border styling to td elements, the left border is not displaying correctly. This issue seems to vary across different browsers. Here is the HTML code: <table class="table-bordered"> <thead> <tr> ...

What is the reason behind Express serving the static file through the router, while also causing the path to the scripts folder to

Directory Layout app ├── app.js ├── public │   ├── data │   │   └── data.json │   ├── index.html │   └── js │   ├── filter-list.js └── routes └── index.js Setting up ap ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

TypeScript React Object.assign method return type

I have a unique custom function that utilizes Object.assign to return a specific result. The documentation mentions that this function returns an array, but surprisingly, it can be destructured both as an array and an object. Check out the code snippet be ...

Trouble getting AngularJS $scope arrays to populate with multiple PHP to MySQL queries

In my Angular controller, I used to fetch data from a PHP file that pulled one query from the database, stored it in a scope array, and displayed it on the webpage successfully. However, now I am trying to execute two queries in the same file. Each query ...

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Clearing a leaflet layer after a click event: Step-by-step guide

When working with my map, I attempt to toggle the layer's selection using a mouse click. Initially, my map looks like this: Upon clicking a layer, my goal is to highlight and select it: If I click on a previously selected layer again, I want to dese ...

The code functions properly on a standalone device, however, it encounters issues when

I am facing an issue with my JavaScript code. It works perfectly fine when I run it on my local machine, but once I upload it to the server, it only functions properly after I refresh the page. Below is the code in question. Please do not hesitate to rea ...

Harnessing the power of the bluebird promise library

Within myPeople function, there is a promise function being called as shown below: var myPeople = function(){ var go; return new Promise (function(resolve){ User .getPeople() .then(function(allPeople){ ...

React component encountering unexpected prop value

In my project, I have a Modal component and a Form component. The Modal is a functional component, while the Form is a class component responsible for handling form submissions. The Modal component passes all of its props to the Form component. Within Mod ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

UI experiencing issues with selecting radio buttons

When trying to select a radio button, I am facing an issue where they are not appearing on the UI. Although the buttons can be clicked, triggering a function on click, the selected option is not displayed visually. <div data-ng-repeat="flagInfo in avai ...

Waiting to run a function until a specified function has finished its execution

I have a piece of code that needs to address synchronization issues related to the execution order of MathJax functions. Specifically, I need to ensure that all the MathJax operations are completed before running the setConsoleWidth() function. What is t ...

Obtaining JSON information within the AngularJS Scope

I am delving into the world of AngularJS for the first time and trying to understand it by following this example: http://jsfiddle.net/SAWsA/11/ After successfully acquiring data in JSON format, I encountered no issues. Here is a snippet of the JSON data: ...

Incorrect Reactjs installation technique

When I try to run create-react-app on my Windows PC, only dependencies are being installed with no folders other than node_modules. Even when using Yarn, I haven't been able to progress further. Please assist and thank you in advance for any help. Thi ...

Assign the "this" keyword of App.vue to the Vuex state

I have discovered a workaround for accessing vue-router and other services that only works within a Vue component. By saving the "this" of the Vue app in the state of Vuex within the created option of App.vue. Is this a good approach or could it potential ...