Annotation:
The question is based on a previous question of mine about a color gradient on text selection.
The problem:
I have changed the text selection so that the background now displays a gradient. The text can be selected normally (with the gradient), but the selection also remains permanently.
The question:
Normally, once the user clicks the mouse, the text is no longer selected. Is it possible to create the same with JavaScript? So that a certain style is deleted / hidden somewhere on the page when the mouse is clicked.
The current code:
textSelected = false
function wrapSelectedText() {
var selectedText = window.getSelection().getRangeAt(0);
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
/* Styling */
span.style.backgroundImage = "linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%)";
span.style.backgroundRepeat = "no-repeat";
span.style.backgroundSize = "100% 0.2em";
span.style.backgroundPosition = "0 88%";
span.appendChild(selectedText);
selection.insertNode(span);
textSelected = true;
}
document.onmouseup = document.onkeyup = document.onselectionchange = function() {
wrapSelectedText()
}
document.onmousedown = function() {
if (textSelected == true) {
// Code for deleting style
alert("Unselect")
}
}
::selection {
background: none;
}
<p>This is an example text.</p>