You need to consider the case where the user's selection spans paragraphs. For example (selection boundaries indicated with pipes):
<p>One <b>t|wo</b></p>
<p>Thr|ee</p>
To handle this, you need to wrap and all the text nodes and partial text nodes within the user's selection in <b>
tags while also detecting which text nodes are already bold and leaving them alone. This is non-trivial, and document.execCommand()
handles it all for you, as do the big WYSIWYG editors.
Most browsers allow switching between style modes, allowing you to choose between styling using elements such as <b>
and <i>
or styling using <span>
elements with style attributes. You can do this using the the "StyleWithCSS" command, falling back to "UseCSS" in older browsers. The following switches commands to use the non-CSS version:
try {
if (!document.execCommand("StyleWithCSS", false, useCss)) {
// The value required by UseCSS is the inverse of what you'd expect
document.execCommand("UseCSS", false, !useCss);
}
} catch (ex) {
// IE doesn't recognise these commands and throws.
}
Finally, if you switched to using CSS classes instead of <b>
etc., you could use the CSS class applier module of my Rangy library.
http://stackoverflow.com/questions/9528466/press-button-to-bold-press-again-to-unbold – EricG Jun 28 '12 at 09:37