Overwrite Highlighted Text On Mouseup Text Selection+ Html5/jquery
I have some content generated by a ML model in 100s of paragraphs, each para has some highlighted content. Sometimes, highlighted data is incorrect, we want the user to select the
Solution 1:
Use Range and Selection APIs to control selection of text nodes. Instead of using <span>
, use <mark>
tags.
Reasons to use <mark>
- 100% semantic
- It's use is uncommon which means there's very little chance of CSS selector conflicts.
- By default it already highlights it's content.
Usage: Highlight text with mouse like you would normally. The <mark>s
do not nest (that's a good thing). In order to remove a highlighted area, click it using the right mouse button.
constmark = event => {
const current = event.currentTarget;
const target = event.target;
const select = document.getSelection();
if (event.which === 1) {
const range = select.getRangeAt(0);
const text = range.toString();
const content = range.extractContents();
const mark = document.createElement('MARK');
mark.textContent = text;
range.insertNode(mark);
} elseif (event.which === 3) {
event.preventDefault();
if (target.tagName === 'MARK') {
const text = target.textContent;
const tNode = document.createTextNode(text);
target.parentNode.replaceChild(tNode, target);
}
}
select.removeAllRanges();
current.normalize();
returnfalse;
}
$(document).on("contextmenu mouseup", mark);
::selection {
background: tomato;
color: white;
}
<p> Contrary to popular belief, <mark>Lorem</mark>Ipsum is not simply random text. It has roots in a piece of popular classical Latin literature from 45 <mark>BC</mark>, making it over 2000 years old.</p><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Post a Comment for "Overwrite Highlighted Text On Mouseup Text Selection+ Html5/jquery"