Change CSS of Selected Text Using JavaScript

Change CSS of selected text using Javascript

The easiest way to do this is to use execCommand(), which has a command to change the background colour in all modern browsers.

The following should do what you want on any selection, including ones spanning multiple elements. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.

UPDATE

Fixed in IE 9.

function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}

function highlight(colour) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}

Change font for selected text using JavaScript

Trying to enhance Ankit's answer,

Here is a solution that doesn't use the replace() function.

The issue with Ankit's solution is that the first occurence of a selected text was replaced in case of a text being repeated.

For example, when the text is "abc abc" and we selected the second one, that was the first one that got its font changed.



The snippet below creates a new html element with the selected text and the chosen font, then deletes the selection and inserts the new element at its place:

(See comments in the code)

function changeFont(font) {  var sel = window.getSelection(); // Gets selection  if (sel.rangeCount) {    // Creates a new element, and insert the selected text with the chosen font inside    var e = document.createElement('span');    e.style = 'font-family:' + font.value + ';';     e.innerHTML = sel.toString();
// https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt var range = sel.getRangeAt(0); range.deleteContents(); // Deletes selected text… range.insertNode(e); // … and inserts the new element at its place }}
.editable {  width: 360px;  height: 120px;  border: 1px solid #ccc}
Highlight text and change font <br><select id="select_font" onchange="changeFont(this);">  <option value="Arial">Arial</option>  <option value="Sans Serif" selected>Sans Serif</option>  <option value="Comic Sans MS">Comic Sans MS</option>  <option value="Times New Roman">Times New Roman</option>  <option value="Courier New">Courier New</option>  <option value="Verdana">Verdana</option>  <option value="Trebuchet MS">Trebuchet MS</option>  <option value="Arial Black">Arial Black</option>  <option value="Impact">Impact</option>  <option value="Bookman">Bookman</option>  <option value="Garamond">Garamond</option>  <option value="Palatino">Palatino</option>  <option value="Georgia">Georgia</option></select><div contenteditable="true" class="editable">  Some Content</div>

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>

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 selected text color easily?

CSS custom properties / CSS Variables will be a better approach.

You can do something like this:

const root = document.documentElement;
const darkMode = document.getElementById("darkMode");

darkMode.addEventListener("click", () => {
root.style.setProperty("--selectionBG", "blueviolet");
root.style.setProperty("--selectionColor", "turquoise");

document.body.style.backgroundColor = "#111";
document.body.style.color = "#eee";
});
:root {
--selectionBG: cyan;
--selectionColor: navy;
}

::selection {
color: var(--selectionColor);
background: var(--selectionBG);
}
<body>
<button id="darkMode">Dark Mode</button>

<h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet natus quia minus cum.</h1>
</body>


Related Topics



Leave a reply



Submit