Change Text Selection Highlight with Js

Change text selection highlight with JS

There's no DOM interface for manipulating pseudo-classes. The only thing you can do is add the rules to a stylesheet. For instance:

// Get the first stylesheet 
var ss = document.styleSheets[0]

// Use insertRule() for standards, addRule() for IE
if ("insertRule" in ss) {
ss.insertRule('div.txtArea::-moz-selection { background: transparent; }', 0);
ss.insertRule('div.txtArea::selection { background: transparent; }', 0);
ss.insertRule('div.txtArea::-webkit-selection { background: transparent; }', 0);
}

You can access and change rules using stylesheet.cssRules[index].style, stylesheet.rules[index].style for IE, which is where it gets a little more complicated.

I didn't include an IE6-8 example using addRule() because those versions of IE don't support ::selection.

How to change the highlight color of selected text in a textarea, using selection range?

I don't understand exactly what you want.

Did you want an answer like the code below?

https://codepen.io/jyh7a/pen/xxpLMZZ

HTML

<input type="text" id="text-box" size="20" value="Mozilla">
<button onclick="selectText()">Select text</button>

<hr/>

<textarea rows="6" cols="40">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</textarea>

<hr/>

<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Porro maxime excepturi autem nostrum minus quae magni, esse optio ab, dolor ut iste earum sapiente molestiae nihil totam rem ipsam officia?</p>

CSS

::selection {
background-color: rgba(255,0,0,0.2);
}

JS

function selectText() {

const input = document.getElementById('text-box');
input.focus();
input.setSelectionRange(2, 5);

setTimeout(() => {
const textarea = document.querySelector('textarea');
textarea.focus();
textarea.setSelectionRange(0, 20);
}, 1000)


// // ERROR!
// // setSelectionRange function only use HTMLInputElements
// const p = document.querySelector('p');
// p.setSelectionRange(0, 20);
}

I searched for setSelectionRange

I made the above example by looking at the MDN official documentation.

(Link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange )

Hope the above code was helpful to you.

Change text highlight color in JavaScript

You could create a style element and place it in the head with the appropriate CSS that you need. A variation on: https://stackoverflow.com/a/524721/23528

var css = 'element::selection { color: red; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet){
// This is required for IE8 and below.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}

head.appendChild(style);

Permanently change selected text background color

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);

how can i change selected text color using javascript

Finally got this,

My solution was,

        var x = document.getElementById("elementID");
function eventCopy() {
x.style.color = 'black';
x.addEventListener("mousemove", eventDispatch);
}
function eventDispatch() {
x.style.color = 'white';
console.log('h');
x.removeEventListener("mousemove", eventDispatch);
}
x.addEventListener("copy",eventCopy);

Change font on highlighted text using JavaScript

Changing font of text within the Textarea won't work but will work for other properties like color, cursor etc.

A workaround is to use a content editable <div>. You can get the selected text with window.getSelection and then wrap with a <span>, after you can apply the style to span's content. As shown below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>E-commerce Website</title> <script> function selectFont() { selectedText = window.getSelection().toString(); NoteHeader = document.getElementById("note_header"); EditedText = NoteHeader.innerText.replace(selectedText, `<span style="font-family: cursive">${selectedText} </span>`); NoteHeader.innerHTML = EditedText; } </script></head>
<body> Highlight text and change font <br> <select id="select_font" onchange="selectFont()"> <option>Select a font</option> <option>Cursive</option> </select> <div contenteditable="true" id="note_header" style="width:200px; height:200px; border: 1px solid #ccc"> Some Content </div></body>
</html>

Is there any way to change background color of ::selection (selected text) using JavaScript?

In general where it's not possible to directly change pseudo element settings via JS it is possible to set CSS variables using JS.

So if you have something like this in your stylesheet:

::selection {
background-color: var(--selcolor);
}

and something like this in your JS:

   element.style.setProperty('--selcolor', selcolor)

it will work.

Here's small example. It changes the selection color variable in the body:

function selChange(color) {
document.body.style.setProperty('--selcolor', color);
}
body {
--selcolor: yellow;
}

::selection {
background-color: var(--selcolor);
}
<button onclick="selChange('cyan');">Cyan</button>
<button onclick="selChange('magenta');">Magenta</button>
<button onclick="selChange('yellow');">Yellow</button>
<p>Highlight some of this text, then click a color and highlight some text...</p>


Related Topics



Leave a reply



Submit