I want to build a unique, simple text editor. With this JS code I can get the selected text from the textarea, but how may I give styling to it (font-weight, font-style etc.) with buttons (Bold, Italic)?
var selectedText = '';
function getText(e) {
selectedText = (document.all) ? document.selection.createRange().text : document.getSelection();
alert(selectedText);
}
document.onmouseup = getText;
if (!document.all) document.captureEvents(Event.MOUSEUP);
I experimented with adding the following code into the getText function. It works at some point, the selected text is wrapped into a span, the span gets the .new-span, bold-style and italic-style classes (btn onclick), but still the styling does not apply to the selected text in the textarea, the change is not visible.
var selectedText = '';
function getText(e) {
selectedText = (document.all) ? document.selection.createRange().text : document.getSelection();
var newSpan = document.createElement("span");
newSpan.classList.add("new-span");
newSpan.innerText += selectedText;
console.log(newSpan);
artParag.appendChild(newSpan);
var boldStyleBtn = document.querySelector(".bold-style-btn");
var italicStyleBtn = document.querySelector(".italic-style-btn");
boldStyleBtn.addEventListener("click", function boldStyle() {
newSpan.classList.toggle("bold-style");
alert(selectedText);
});
italicStyleBtn.addEventListener("click", function italicStyle() {
newSpan.classList.toggle("italic-style");
alert(selectedText);
});
}
document.onmouseup = getText;
if (!document.all) document.captureEvents(Event.MOUSEUP);
(the CSS):
.bold-style {
font-weight: 700;
}
.italic-style {
font-style: italic;
}
Is this a good direction? Thank you in advance for your help.