How can I permanently change the background color of text when I select it ? What I am trying to achieve is a highlight effect like this:
Anyone can instruct me how to accomplish this with javascript?
I appreciate your help a lot.
CodePudding user response:
Use ::selection
selector to override the default color:
::selection{
background: #FFD24D;
}
<p>A team of horses will struggle to chase down a spoken word.</p>
CodePudding user response:
You need to add event listener in javascript and when a text is selected at that time need to change the color like below
function logSelection(event) {
// Get Selection
sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
// Set design mode to on
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Colorize text
document.execCommand("ForeColor", false, "red");
// Set design mode to off
document.designMode = "off";
}
const input = document.querySelector('input');
input.addEventListener('select', logSelection);