With my current use of JavaScript, I am able to highlight or bold a selected text range successfully. However, I am unsure how to undo the bold and unhighlight the text if the button is clicked again and the selected range is already bolded or highlighted.
I am unable to use doc.execCommand or jQuery due to using it in an Android webview. Using doc.execCommand takes a significant amount of time (1 second or more) to work on large texts, whereas JavaScript functions instantaneously. Utilizing jQuery (zepto or others) causes the text to load very slowly in the webview, while without it, the loading time is at most 1 or 2 seconds.
=)
This is what I currently have to make the selected text bold:
function bold() {
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.appendChild(selectionContents);
span.setAttribute("class","bold");
span.style.fontWeight = "bold";
range.insertNode(span);
}
And for highlighting (note: color will be chosen by the user through a color picker and returned as #xxxxxx):
function foreground() {
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.appendChild(selectionContents);
span.setAttribute("class","foreground");
span.style.color = "#" + colorbyUser;
range.insertNode(span);}
I believe that styling such as bold/italic/strike/strikethrough/underline can be achieved with specific CSS classes added or removed easily. However, adjusting background and foreground colors may require individual handling for each selection (letter/word or more).
Apologies for the imperfect English =x
Edit for C-smile
I understand now, but I am uncertain how to target the element in this scenario:
<span class="bold">Hello <span class="underline">C</span>-<span class="italic">Smile</span></span>
How can I remove the bold from "Hello" if only "HelLo" is selected, without affecting the bold formatting of "C-Smile"?
Is this achievable without relying on jQuery (which slows down loading time for big documents) or doc.execCommand (slows down processing time for big documents)?