`On mouseup event, changing specific text`

I've been working on a real-time HTML highlighter that surrounds selected text with span elements containing a background property.

Check out the fiddle here: https://jsfiddle.net/4hd2vrex/

The issue arises when users make multiple selections, leading to nested spans and messy content like this:

<span style="background-color: rgb(255, 255, 131);">
    r
    <span style="background-color: rgb(255, 255, 131);">
        <span style="background-color: rgb(255, 255, 131);">
            e
        </span>
        p
    </span>
    r
    <span style="background-color: rgb(255, 255, 131);">
        e
    </span>
    h
    <span style="background-color: rgb(255, 255, 131);">
        end
    </span>
    e
    <span style="background-color: rgb(255, 255, 131);">
        rit
    </span>
</span>

To address this mess, I came up with the following solution:

Instead of adding more spans, just replace all the selected text - including any existing span tags - with the original selection using window.getSelection().

For instance, if I were to select the jumble of spans above, I would first replace them with window.getSelection(), which is simply the text reprehenderit, resulting in:

<span style="background-color: rgb(255, 255, 131);">reprehenderit</span>

Q: How can I swap my selection for the selected text?

Answer №1

I found an interesting way to highlight text using my own methods instead of the window.Selection API. I use

select(start,end).then(merge).then(filter).then(highlight)
to accomplish this. What's fascinating is that this method allows for highlighting complex elements, not just plain text. I also discovered that the select API can be used to create a WYSIWYG HTML editor. I wanted to share this solution with anyone interested in selection problems. Hopefully, it helps you too! Good question!

(function (context, factory) {
    if (typeof module != 'undefined' && typeof module.exports == 'object') {
        module.exports = factory(context);
    } else {
        factory(context, true);
    }
})(window || this, function (context, bind) {
    function promise(executor) {
        return new Promise(executor);
    }

    var $TYPE = 'nodeType', $TEXT = 'textContent', $PARENT = 'parentNode', $NEXT = 'nextSibling', $FIRST = 'firstChild', NIL = {};

    // More JavaScript code here...

})();
// CSS styling code here...
// Additional script and HTML content here...

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

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

When exporting a Mongoose model, it mysteriously becomes undefined

I am encountering an issue when trying to import the DemandeTransports model from a specific file: //@/components/database/model/Schema.js import { Schema } from "mongoose"; import mongoose from "mongoose"; const userSchema = new Schem ...

Choosing values from a variety of select option boxes using jQuery

I'm experiencing an issue with selecting values in a multiple select option box. Despite my efforts, I haven't been able to get all the desired items selected at once. Currently, when I run the code below, only the first option is being selected ...

Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png If you are facing the error/missing CSS, check out this video for a visual representation. While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not ...

How do I select the first element with class "cell" in D3, similar to jQuery's $(".cell:first")?

I have attempted this: d3.select(".cell:first") d3.selectAll(".cell").filter(":first") d3.selectAll(".cell").select(":first") but unfortunately, none of these methods are effective. ...

Executing Selenium tests: utilizing the webdriver.wait function to repeatedly call a promise

Currently, I am using Selenium ChromeDriver, Node.js, and Mocha for testing purposes... I am facing a dilemma at the moment: The driver.wait function seamlessly integrates with until. I have a promise, which we'll refer to as promiseA. This pro ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

hide input type with minimal display

Can someone help me find the less equivalent to this css code snippet? I'm not familiar with less and this code is part of a larger global css file that includes generated code from all less files. input[type="checkbox"] { display: none; } Any a ...

Allow users to select options after they click a radio button

I have a pair of radio buttons and two sets of select options within different classes. Upon selecting the first radio button, the select options belonging to class1 should be enabled. On the other hand, upon selecting the second radio button, the select ...

I have created a textbox with a button, but I am unsure of how to delete it

var emailFields = document.getElementById('emails'), addLinkButton = document.createElement('a'), fieldTemplate = emailFields.getElementsByTagName('div'), currentFieldCount = fieldTemplate.length, maxFields ...

Disappearing markers issue in Openlayers when zooming

I am trying to ensure that markers on the map do not get erased when zooming in or out. Here is my script: JS $(document).ready(function() { //initialization var map; var markerPosition; // Marker position var options = { restrictedE ...

Tips for merging ajax div elements

Here's a combination of my Ajax scripts, integrating the first and second versions: 1st <script> function Ajax() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp ...

Create a server directory structure that populates multiple HTML dropdown lists using either jQuery or AJAX

As a novice navigating jQuery and Ajax, I find myself faced with a specific challenge. My current situation involves a structured set of directories on a server. My goal is to populate a dropdown dynamically with this file hierarchy. Upon click ...

Utilizing React JS and lodash's get method within a single function

Is it possible to display two string objects in the same line using Lodash get? Can I achieve this by chaining (_.chain(vehicle).get('test').get('test2))? Below is a snippet of the JSON file: { "results": [ { " ...

What could be causing the getTotals() method to malfunction?

I have been working on a finance app that is designed to update the "income", "expenses", and "balance" tables at the top each time a new item is added by the user. However, the current code seems to be failing in updating these values correctly based on u ...

Having trouble with Bootstrap v4 dropdown menu functionality?

For some reason, I cannot get the dropdown menu to work in my Bootstrap v4 implementation. I have tried copying and pasting the code directly from the documentation, as well as testing out examples from other sources on separate pages with no luck. &l ...

Is there a way to retrieve the same post from one controller and access it in another?

Hello, I am currently exploring the world of Full Stack web development and have stumbled upon a challenge. My tech stack includes mongodb, mongoose, node, and express. Within my project, I have implemented two controllers - one for user signup and anothe ...

Can you suggest a method to save cookies or HTML5 localStorage across multiple WebBrowser instances on Windows Phone?

Quick question: How can I save data from Javascript in a WebBrowser control on my Windows Phone 8 app so that it remains even after the user closes and reopens the app? In more detail: I am working on a Windows Phone 8 app with a single WebBrowser contro ...

Creating a multi-page app using React: A comprehensive guide

I am in the process of developing an application using NodeJS, and I have decided to incorporate React for creating interactive components within the app. However, my goal is to avoid turning it into a single-page application. How can I effectively distri ...

Having trouble properly removing an item from an array using splice() function

I'm facing an issue with an array where I need to remove a specific object. I attempted using the splice() method, but upon implementation, it ends up removing all objects except the one that was found. Here's a snippet of my JavaScript code: On ...