JSFiddle - React, Tailwind, and code Playground
by Imri Paloja
HTML
<button class="boldtrigger">Bold</button>
<div class="text">Testing the waters</div>
CSS
.selectedText {
font-weight: bold;
}
JavaScript
$(".boldtrigger").click(function() {
var selection = getSelText();
console.log('selected value', selection);
//only bold text that is selected
//get contents of .text
//replace selected section with <span class="selectedText"></span>
//ex: user selects the word "the" with the mouse:
//<div class="text">Testing the waters</div> becomes:
//<div class="text">Testing <span class="selectedText">the</span> waters</div>
//then bold contents of .selectedText
var range = selection.getRangeAt(0);
if (selection.toString().length > 2) {
var newNode = document.createElement("span");
newNode.setAttribute("class", "selectedText");
range.surroundContents(newNode);
}
});
function getSelText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
} else return;
return txt;
}